php - GCM 与 PHP(谷歌云消息)

标签 php android firebase-cloud-messaging google-cloud-messaging

Update: GCM is deprecated, use FCM

如何集成新的 Google Cloud Messaging在 PHP 后端?

最佳答案

此代码将通过 PHP CURL 向多个注册 ID 发送 GCM 消息。

// Payload data you want to send to Android device(s)
// (it will be accessible via intent extras)    
$data = array('message' => 'Hello World!');

// The recipient registration tokens for this notification
// https://developer.android.com/google/gcm/    
$ids = array('abc', 'def');

// Send push notification via Google Cloud Messaging
sendPushNotification($data, $ids);

function sendPushNotification($data, $ids) {
    // Insert real GCM API key from the Google APIs Console
    // https://code.google.com/apis/console/        
    $apiKey = 'abc';

    // Set POST request body
    $post = array(
                    'registration_ids'  => $ids,
                    'data'              => $data,
                 );

    // Set CURL request headers 
    $headers = array( 
                        'Authorization: key=' . $apiKey,
                        'Content-Type: application/json'
                    );

    // Initialize curl handle       
    $ch = curl_init();

    // Set URL to GCM push endpoint     
    curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');

    // Set request method to POST       
    curl_setopt($ch, CURLOPT_POST, true);

    // Set custom request headers       
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    // Get the response back as string instead of printing it       
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Set JSON post data
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));

    // Actually send the request    
    $result = curl_exec($ch);

    // Handle errors
    if (curl_errno($ch)) {
        echo 'GCM error: ' . curl_error($ch);
    }

    // Close curl handle
    curl_close($ch);

    // Debug GCM response       
    echo $result;
}

关于php - GCM 与 PHP(谷歌云消息),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11242743/

相关文章:

apache - 这些配置更改是否适合我的需要?

java - 无法在 Android Studio 中添加操作栏项目

c# - 如何使用 .net admin sdk 添加指向 firebase 云消息传递的链接

php - 如何计算PHP中JSON值的长度?

php - 如何获取在 Laravel 5.3 中执行的最后一个查询?

android - 来自 Android 蓝牙不安全 Rfcomm 的 "Service discovery failed"

android - 应用程序运行时不显示 Firebase 通知

firebase - 在 Flutter 中,我们如何使用 Firebase Messaging onBackgroundMessage 创建通知,使用 flutter_local_notifications?

php - 当修改一条sql记录时,它正在修改所有表

Android:有没有人遇到localhost HttpClient Connection Refused 错误?