Ela*_*ava 236

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

// 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我在哪里可以获得注册ID? (9认同)
  • 谢谢你的回答!如果这对任何人都有用,我将它汇总到PHP对象框架中:https://github.com/kaiesh/GCM_PHP (6认同)
  • @Sit禁用SSL证书检查总是一个坏主意.如果您的服务器无法验证SSL证书,请使用此技术告诉cURL期望的证书:http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access- https -ssltls-protected-sites /或强制cURL使用cURL网站上的最新cacert.pem,使用以下内容:https://gist.github.com/gboudreau/5206966 (6认同)
  • 这有助于:`curl_setopt($ ch,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);` (4认同)
  • 它几乎在这里工作,但我没有在手机上收到任何消息.我想调试它,但我不知道为什么我的$ result总是空的... (3认同)

小智 34

<?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);
?>
Run Code Online (Sandbox Code Playgroud)

  • 嗨Shailesh Giri,使用**浏览器密钥**工作正常,但在服务器密钥的情况下,它显示**未授权错误401**.你能帮我吗. (3认同)
  • `curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false);`是一个很大的禁忌.如果由于某种原因,运行此PHP代码的服务器无法验证Google服务器使用的SSL证书,您可以告诉cURL要验证的内容.示例:http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/ (3认同)

Rog*_*mas 18

这很容易做到.该卷曲的代码就是这样埃拉德纳瓦已经把这里的工作在页面上.Elad 评论了他收到的错误.

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

我已经设置了一个似乎正在运行的服务(ish),到目前为止我所有的回复都是谷歌提供的.这很可能会很快改变.

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

<?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);
Run Code Online (Sandbox Code Playgroud)

我们终于得到它了.在Zend Framework PHP中使用Googles new GCM的一个工作(它将很快工作)的例子.

  • 大规模更新!显然使用带有IP限制的API密钥集无法正常工作.我刚刚在服务器端交换了我的API密钥,以便在API控制台中使用名为"密钥浏览器应用程序(带有引用程序)"的密钥,并猜猜是什么!它经历了.这是我的回复:{"multicast_id":8466657113827057558,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1341067903035991%921c249a66d6cf16"}] } (9认同)

小智 13

经过很长一段时间的搜索后,我终于找到了我真正需要的东西,使用PHP作为服务器端脚本语言连接到GCM,以下教程将让我们清楚地了解如何设置我们开始所需的一切与GCM

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


mwi*_*nks 10

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

这将与ZF 1.12一起发布,但它应该给你一些很好的例子来说明如何做到这一点.

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

<?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']);
    }
}
Run Code Online (Sandbox Code Playgroud)


dex*_*xtr 6

您也可以尝试这段代码,来源:

<?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);
Run Code Online (Sandbox Code Playgroud)


Aba*_*art 6

许多教程已经过时,甚至当前代码也没有说明何时更新设备registration_ids或取消注册设备.如果这些项目未经检查,最终将导致阻止接收邮件的问题. http://forum.loungekatt.com/viewtopic.php?t=63#p181