【问题标题】:Send GCM notifications to multiple devices using PHP使用 PHP 向多个设备发送 GCM 通知
【发布时间】:2017-07-24 08:22:57
【问题描述】:

我需要将 GCM 通知发送到多个设备。在这里,我编写了 PHP 代码以从 MySql 获取注册 ID 数组,并尝试向多个设备发送通知,但这里有一些问题。

我的 PHP 代码:

<?php 
if($_SERVER['REQUEST_METHOD']=='GET'){

$tags  = $_GET['tags'];
 $api_key = 'My OWN API KEY';   

//Getting registration token we have to make it as array 

//Getting the message 
$message = Testing GCM';
$title= 'Cuboid';
$vibrate= '1';
$sound= '1';


require_once('dbConnect.php');

$user_ids = array();

       foreach ($_REQUEST['tags'] as $key => $val) {
       $user_ids[$key] = filter_var($val, FILTER_SANITIZE_STRING);
        }
        $tagss = "'" . implode("','", $user_ids) . "'";
           $sql = "SELECT user_tags.user_id AS userID , gcm_token.regtoken AS regToken
                   FROM user_tags,gcm_token
                    WHERE tags IN ({$tagss}) AND user_tags.user_id=gcm_token.user_id";


$r = mysqli_query($con,$sql);

 //creating a blank array 
 $result = array();
 $reg_token = array();


 //looping through all the records fetched

    while ($row = mysqli_fetch_array($r)) {
    $result['regToken'][] = $row['regToken'];   
      }

     //Displaying the array in json format 

     echo json_encode(array('result'=>$result));

     $reg_token = (json_encode(array('result'=>$result)));
     //$reg_token = array('result'=>$result);


     $msg = array
(
    'message'   => $message,
    'title'     => $title,
    'subtitle'  => 'Android Push Notification using GCM Demo',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => $vibrate,
    'sound'     => $sound,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
);

//Creating a new array fileds and adding the msg array and registration token array here 
$fields = array
(
    'registration_ids'  => $reg_token,
    'data'          => $msg
);

//Adding the api key in one more array header 
$headers = array
(
    'Authorization: key=' . $api_key,
    'Content-Type: application/json'
); 

//Using curl to perform http request 
$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 ) );

//Getting the result 
$results = curl_exec($ch );
curl_close( $ch );

//Decoding json from results 
$res = json_decode($results);

      mysqli_close($con);
    }

【问题讨论】:

  • 每个请求有 1000 个数组的限制。
  • 是的,但是我没有收到任何通知。为什么.?? i Ony 在数组中有 6 个 Reg_Ids
  • 你尝试发送单个令牌?
  • 是的。如果 reg_token 变量是字符串,那么它可以工作.. 但是如果我将它更改为数组,那么它就不能工作..
  • 你可以在这里查看。不对数组进行编码。 stackoverflow.com/questions/11242743/…

标签: php android google-cloud-messaging


【解决方案1】:

您必须在 JSON 数组中获取结果。试试下面的代码:

<?php

if($_SERVER['REQUEST_METHOD']=='GET'){

$tags  = $_GET['tags'];
// Replace with the real server API key from Google APIs
$apiKey = "YOUR_API_CODE";

$message = "Hello Raja";

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


require_once('dbConnect.php');

$user_ids = array();

       foreach ($_REQUEST['tags'] as $key => $val) {
       $user_ids[$key] = filter_var($val, FILTER_SANITIZE_STRING);
        }
        $tagss = "'" . implode("','", $user_ids) . "'";
           $sql = "SELECT user_tags.user_id AS userID , gcm_token.regtoken AS regToken
                   FROM user_tags,gcm_token
                    WHERE tags IN ({$tagss}) AND user_tags.user_id=gcm_token.user_id";

$r = mysqli_query($con,$sql);

$result = array();



 //looping through all the records fetched

  while ($row = mysqli_fetch_array($r)) {
    $result[] = $row['regToken'];   
}

 //Displaying the array in json format 

   //echo json_encode(array('result'=>$result));

     echo json_encode(($result));

            $registrationIDs = ($result);


    //echo json_encode(array('result'=>$result));


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

     ?> 

【讨论】:

    【解决方案2】:

    更新:

    根据updated documentation,发送推送通知的 API 端点从 https://android.googleapis.com/gcm/sendhttps://fcm.googleapis.com/fcm/send

    旧的端点仍在工作,但我建议使用最新的端点。 此代码对于两个端点保持相同。


    试试这个, 声明一个发送通知的函数:

    function sendfcmMessage($registrationIds, $msg)
    {
    
        if (!defined('API_ACCESS_KEY')) define('API_ACCESS_KEY', '<PUT_YOUR_KEY_HERE>');
        $fields = array('registration_ids' => $registrationIds, 'data' => $msg, 'content-available' => 1, 'priority' => 'high'); //set priority as required
        $headers = array('Authorization: key=' . API_ACCESS_KEY, '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);
        curl_close($ch);
        return $result;
    }
    

    这样使用,

        $msg = array('message' => $message,
                'title' => $title, 
                'body' => $body,
                'subtitle' => $subtitle, 
                'tickerText' => $ticker_text, 
                'vibrate' => $vibrate, 
                'sound' => $sound, 
                'largeIcon' => 'large_icon', 
                'smallIcon' => 'small_icon');
    
        $registrationIds = array();
    
        while ($row = mysqli_fetch_array($r)) {
            array_push($registrationIdsIOS, $row['regToken'];);
        }
    
        sendfcmMessage($registrationIds, $msg);
    

    您也可以通过打印此函数的结果来进行调试,以了解是否发送了通知,它还可以让您知道为什么没有发送通知。

    echo sendfcmMessage($registrationIds, $msg);
    

    【讨论】:

      猜你喜欢
      • 2014-11-09
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多