GCM with PHP (Google Cloud Messaging)

后端 未结 13 1459
轮回少年
轮回少年 2020-11-22 04:48

Update: GCM is deprecated, use FCM

How can I integrate the new Google Cloud Messaging in a PHP backend?

13条回答
  •  心在旅途
    2020-11-22 05:23

    ";
    
        $headers = array('Authorization:key=' . $yourKey);    
        $data = array(    
            'registration_id' => $deviceToken,          
            'collapse_key' => $collapseKey,
            'data.message' => $messageText);  
        $ch = curl_init();    
    
        curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");    
        if ($headers)    
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);    
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    
        curl_setopt($ch, CURLOPT_POST, true);    
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
    
        $response = curl_exec($ch);    
        var_dump($response);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);    
        if (curl_errno($ch)) {
            return false;
        }    
        if ($httpCode != 200) {
            return false;
        }    
        curl_close($ch);    
        return $response;    
    }  
    
    $yourKey = "YOURKEY";
    $deviceToken = "REGISTERED_ID";
    $collapseKey = "COLLAPSE_KEY";
    $messageText = "MESSAGE";
    echo sendMessageToPhone($deviceToken, $collapseKey, $messageText, $yourKey);
    ?>
    

    In above script just change :

    "YOURKEY" to API key to Server Key of API console.
    "REGISTERED_ID" with your device's registration ID
    "COLLAPSE_KEY" with key which you required
    "MESSAGE" with message which you want to send

    Let me know if you are getting any problem in this I am able to get notification successfully using the same script.

提交回复
热议问题