Home >php教程 >php手册 >php实现 GCM(Google Cloud Messaging) 云推送消息

php实现 GCM(Google Cloud Messaging) 云推送消息

WBOY
WBOYOriginal
2016-06-06 19:46:201381browse

首先我们要获取api key ,使用google 帐号登录https://code.google.com/apis/console 点击api access 如下 在该页面可以看到申请到的app key 如果没有可以点击 create new server key... 按钮 如下图 获得了app key 下面就简单了 上php代码: ?phpclass push

 首先我们要获取api key ,使用google 帐号登录https://code.google.com/apis/console 点击api access 如下

php实现 GCM(Google Cloud Messaging) 云推送消息

在该页面可以看到申请到的app key  如果没有可以点击 create new server key... 按钮 如下图

php实现 GCM(Google Cloud Messaging) 云推送消息

获得了app key  下面就简单了 上php代码:

<?php class push extends CI_Controller {
	
	function __construct() {
		parent::__construct ();
		$this->load->Model ( 'common' );
		// $this->common->requireLogin ();
	}
	
	function index() {
		
	<span>$reg_id = "APA91bGLGb2AiMM-gLMRKNKqlrsKRJHFjQ1_1XFkmlITjd8X7ucV9WFFAOmkICkMn7hyMqIevkET-XrprY32LtiAuZtzreYYow4aiZCpH_Q04dfOiC85e-bH7NRIMsF0W3BvJ_ki8PE5"</span>;
	$msg = "00000";
 
	$this->send_gcm_notify($reg_id, $msg);
	}
	
	function send_gcm_notify($reg_id, $message) {
 
    $fields = array(
        'registration_ids'  => array( $reg_id),
        'data'              => array( "message" => $message ),
    );
 
    $headers = array(
        'Authorization: key=' . 'AIzaSyBV4VW7n9AJdJwox9MUwC******',<span>//获取到的app key</span>
        'Content-Type: application/json'
    );
 
    $ch = curl_init();
    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_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:是app中调用gcm.jar中的方法获取到的,如下。在该测试代码中我们在服务端写死该ID.
import com.google.android.gcm.GCMRegistrar;

 final String regId = GCMRegistrar.getRegistrationId(this);

整个推送系统的交互应该是:

  1.客户端app运行,成功获取 regId ,将该ID发送到服务端,存入数据库。

  2.服务端根据某些特定的条件选择出regId,而后调用google 推送服务。


推送成功返回如下:

{
   multicast_id: 5381354139383071000,
   success: 1,
   failure: 0,
   canonical_ids: 0,
   results: [
    {
      message_id: "0:1377835083519762%2adac3a0f9fd7ecd"
    }
   ]
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn