1

我正在编写一个 php 脚本以将通知发送到 CGM 服务器,并且我正在使用以下示例:

public function send_notification($registatoin_ids, $message) { // 包含配置 include_once './config.php';

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

    $fields = array(
        'registration_ids' => $registatoin_ids,
        'data' => $message,
    );

    $headers = array(
        'Authorization: key=' . GOOGLE_API_KEY,
        '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);

    // Disabling SSL Certificate support temporarly
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    // Execute post
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }

    // Close connection
    curl_close($ch);
    echo $result;
}

但我不确定变量的值应该是什么: CURLOPT_POSTFIELDS 、 CURLOPT_SSL_VERIFYPEER 、 CURLOPT_RETURNTRANSFER 、 CURLOPT_HOST 、 CURLOPT_URL

有人会碰巧知道这些值应该是什么吗?

谢谢!

4

1 回答 1

2

“ CURLOPT_POSTFIELDS ” 此字段是推送json编码格式的字段数所必需的。如果您的第三方服务器是基于 SSL 的 HTTPS,则“CURLOPT_SSL_VERIFYPEER”此字段是必需的。"CURLOPT_RETURNTRANSFER" 此字段为您提供来自 gcm 服务器的回复。"CURLOPT_HOST , CURLOPT_URL" 此字段用于您必须为第三方服务器定义的主机名称和 URL。

那是我已经实现的解码代码:

<?php
$apiKey = "Your Api Key"; 
$reg_id = array("Your registration ID that we have get from device");
$registrationIDs = $reg_id;

// Message to be sent
$message = $_REQUEST['message']; 

// 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;
?>

根据我的经验,此链接将对您有所帮助:

GCM 与 PHP(谷歌云消息)

http://www.sherif.mobi/2012/07/gcm-php-push-server.html

https://groups.google.com/forum/#!topic/android-gcm/hjk5PUYlTp0

于 2012-10-20T04:08:17.547 回答