0

我正在尝试向配置了 Google Cloud Messaging 的应用程序发送消息。我有一个我认为设置正确的 php 函数。

    function send($message){
            $devices = array ('deviceid');
            $serverApiKey = 'apiKey';

    $fields = array(
        'registration_ids'  => $this->devices,
        'data'              => array( "message" => $message ),
    );

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

    error_reporting(-1);
    // Open connection
    $ch = curl_init();

    // Set the url, number of POST vars, POST data
    curl_setopt( $ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
    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 ) );

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

    print_r(curl_getinfo($ch));

    // Close connection
    curl_close($ch);

    return $result;
}

但 Curl 从未接受过请求。似乎什么都没有通过。print_r 代码打印出来:

Array ( [url] => https://android.googleapis.com/gcm/send [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.031 [namelookup_time] => 0 [connect_time] => 0.047 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => Array ( ) [redirect_url] => )

有谁知道我做错了什么?我还将提到我在安装了 WAMP 服务器的 Windows 机器上运行此脚本。卷曲已启用。我完全不知道为什么它不起作用。

4

2 回答 2

0

没关系。如果有人想知道,我可以通过添加

curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
于 2013-05-24T20:31:09.217 回答
0

你也可以使用这个 PHP 库:

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

安装后你可以这样做:

$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();

}

发送后即可得到响应。

于 2015-03-13T03:06:51.557 回答