Android 带有 PHP 的 GCM(谷歌云消息传递)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11242743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:28:44  来源:igfitidea点击:

GCM with PHP (Google Cloud Messaging)

phpandroidfirebase-cloud-messaginggoogle-cloud-messaging

提问by user1488243

Update:GCMis deprecated, use FCM

更新:不推荐使用GCM,使用FCM

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

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

回答by Elad Nava

This code will send a GCM message to multiple registration IDs via PHP CURL.

此代码将通过 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;
}

回答by Shailesh Giri

<?php
    // Replace with the real server API key from Google APIs
    $apiKey = "your api key";

    // Replace with the real client registration IDs
    $registrationIDs = array( "reg id1","reg id2");

    // Message to be sent
    $message = "hi Shailesh";

    // Set POST variables
    $url = 'https://android.googleapis.com/gcm/send';

    $fields = array(
        'registration_ids' => $registrationIDs,
        'data' => array( "message" => $message ),
    );
    $headers = array(
        'Authorization: key=' . $apiKey,
        'Content-Type: application/json'
    );

    // Open connection
    $ch = curl_init();

    // Set the URL, number of POST vars, POST data
    curl_setopt( $ch, CURLOPT_URL, $url);
    curl_setopt( $ch, CURLOPT_POST, true);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // curl_setopt($ch, CURLOPT_POST, true);
    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));

    // Execute post
    $result = curl_exec($ch);

    // Close connection
    curl_close($ch);
    echo $result;
    //print_r($result);
    //var_dump($result);
?>

回答by Roger Thomas

It's easy to do. The cURLcode that's on the page that Elad Nava has put here works. Elad has commented about the errorhe's receiving.

这很容易做到。该卷曲的代码是这样的页面埃拉德纳瓦在这里把工程对。Elad他收到的错误发表了评论

String describing an error that occurred while processing the message for that recipient. The possible values are the same as documented in the above table, plus "Unavailable" (meaning GCM servers were busy and could not process the message for that particular recipient, so it could be retried).

描述在处理该收件人的邮件时发生的错误的字符串。可能的值与上表中记录的值相同,加上“不可用”(意味着 GCM 服务器很忙,无法处理该特定收件人的消息,因此可以重试)。

I've got a service set up already that seems to be working (ish), and so far all I've had back are unavailable returns from Google. More than likely this will change soon.

我已经设置了一个似乎正在运行的服务(ish),到目前为止,我所拥有的一切都是无法从 Google 返回的。这很可能很快就会改变。

To answer the question, use PHP, make sure the Zend Frameworkis in your include path, and use this code:

要回答这个问题,请使用 PHP,确保Zend 框架在您的包含路径中,并使用以下代码:

<?php
    ini_set('display_errors',1);
    include"Zend/Loader/Autoloader.php";
    Zend_Loader_Autoloader::getInstance();

    $url = 'https://android.googleapis.com/gcm/send';
    $serverApiKey = "YOUR API KEY AS GENERATED IN API CONSOLE";
    $reg = "DEVICE REGISTRATION ID";

    $data = array(
            'registration_ids' => array($reg),
            'data' => array('yourname' => 'Joe Bloggs')
    );

    print(json_encode($data));

    $client = new Zend_Http_Client($url);
    $client->setMethod('POST');
    $client->setHeaders(array("Content-Type" => "application/json", "Authorization" => "key=" . $serverApiKey));
    $client->setRawData(json_encode($data));
    $request = $client->request('POST');
    $body = $request->getBody();
    $headers = $request->getHeaders();
    print("<xmp>");
    var_dump($body);
    var_dump($headers);

And there we have it. A working (it will work soon) example of using Googles new GCM in Zend Framework PHP.

我们终于得到它了。在 Zend Framework PHP 中使用 Google 的新 GCM 的工作(很快就会工作)示例。

回答by Yoga Sai Krishna

After searching for a long time finally I am able to figure out what I exactly needed, Connecting to the GCM using PHP as a server side scripting language, The following tutorial will give us a clear idea of how to setup everything we need to get started with GCM

经过长时间的搜索,我终于能够弄清楚我到底需要什么,使用 PHP 作为服务器端脚本语言连接到 GCM,下面的教程将让我们清楚地了解如何设置我们需要开始的一切带 GCM

Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL

使用 Google Cloud Messaging (GCM)、PHP 和 MySQL 的 Android 推送通知

回答by mwillbanks

I actually have this working now in a branch in my Zend_Mobile tree: https://github.com/mwillbanks/Zend_Mobile/tree/feature/gcm

我实际上现在在我的 Zend_Mobile 树的一个分支中工作:https: //github.com/mwillbanks/Zend_Mobile/tree/feature/gcm

This will be released with ZF 1.12, however, it should give you some great examples on how to do this.

这将与 ZF 1.12 一起发布,但是,它应该为您提供一些有关如何执行此操作的很好的示例。

Here is a quick demo on how it would work....

这是一个关于它如何工作的快速演示......

<?php
require_once 'Zend/Mobile/Push/Gcm.php';
require_once 'Zend/Mobile/Push/Message/Gcm.php';

$message = new Zend_Mobile_Push_Message_Gcm();
$message->setId(time());
$message->addToken('ABCDEF0123456789');
$message->setData(array(
    'foo' => 'bar',
    'bar' => 'foo',
));

$gcm = new Zend_Mobile_Push_Gcm();
$gcm->setApiKey('MYAPIKEY');

$response = false;

try {
    $response = $gcm->send($message);
} catch (Zend_Mobile_Push_Exception $e) {
    // all other exceptions only require action to be sent or implementation of exponential backoff.
    die($e->getMessage());
}

// handle all errors and registration_id's
foreach ($response->getResults() as $k => $v) {
    if ($v['registration_id']) {
        printf("%s has a new registration id of: %s\r\n", $k, $v['registration_id']);
    }
    if ($v['error']) {
        printf("%s had an error of: %s\r\n", $k, $v['error']);
    }
    if ($v['message_id']) {
        printf("%s was successfully sent the message, message id is: %s", $k, $v['message_id']);
    }
}

回答by dexxtr

Also you can try this piece of code, source:

你也可以试试这段代码,来源

<?php
    define("GOOGLE_API_KEY", "AIzaSyCJiVkatisdQ44rEM353PFGbia29mBVscA");
    define("GOOGLE_GCM_URL", "https://android.googleapis.com/gcm/send");

    function send_gcm_notify($reg_id, $message) {
        $fields = array(
            'registration_ids'  => array( $reg_id ),
            'data'              => array( "message" => $message ),
        );

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

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL);
        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);
        if ($result === FALSE) {
            die('Problem occurred: ' . curl_error($ch));
        }

        curl_close($ch);
        echo $result;
    }

    $reg_id = "APA91bHuSGES.....nn5pWrrSz0dV63pg";
    $msg = "Google Cloud Messaging working well";

    send_gcm_notify($reg_id, $msg);

回答by Abandoned Cart

A lot of the tutorials are outdated, and even the current code doesn't account for when device registration_ids are updated or devices unregister. If those items go unchecked, it will eventually cause issues that prevent messages from being received. http://forum.loungekatt.com/viewtopic.php?t=63#p181

很多教程已经过时了,甚至当前的代码也没有说明设备注册 ID 何时更新或设备注销。如果未选中这些项目,最终会导致无法接收消息的问题。 http://forum.loungekatt.com/viewtopic.php?t=63#p181

回答by Ajit

<?php

function sendMessageToPhone($deviceToken, $collapseKey, $messageText, $yourKey) {    
    echo "DeviceToken:".$deviceToken."Key:".$collapseKey."Message:".$messageText
            ."API Key:".$yourKey."Response"."<br/>";

    $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

“YOURKEY”到 API 控制台的服务器密钥的 API 密钥。
“REGISTERED_ID” 带有您设备的注册 ID
“COLLAPSE_KEY” 带有您需要的密钥
“MESSAGE” 带有您要发送的消息

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

如果您在这方面遇到任何问题,请告诉我,我可以使用相同的脚本成功收到通知。

回答by chrisbjr

You can use this PHP library available on packagist:

您可以使用 packagist 上提供的这个 PHP 库:

https://github.com/CoreProc/gcm-php

https://github.com/CoreProc/gcm-php

After installing it you can do this:

安装后,您可以执行以下操作:

$gcmClient = new GcmClient('your-gcm-api-key-here');

$message = new Message($gcmClient);

$message->addRegistrationId('xxxxxxxxxx');
$message->setData([
    'title' => 'Sample Push Notification',
    'message' => 'This is a test push notification using Google Cloud Messaging'
]);

try {

    $response = $message->send();

    // The send() method returns a Response object
    print_r($response);

} catch (Exception $exception) {

    echo 'uh-oh: ' . $exception->getMessage();

}

回答by Steve Tauber

Here's a library I forked from CodeMonkeysRU.

这是我从 CodeMonkeysRU 分叉出来的一个库。

The reason I forked was because Google requires exponential backoff. I use a redis server to queue messages and resend after a set time.

我分叉的原因是因为谷歌需要指数退避。我使用 redis 服务器来排队消息并在设定的时间后重新发送。

I've also updated it to support iOS.

我还更新了它以支持 iOS。

https://github.com/stevetauber/php-gcm-queue

https://github.com/stevetauber/php-gcm-queue