使用GCM向所有用户发送推送消息

时间:2016-05-31 19:14:32

标签: php android mysql push-notification

我正在尝试向我的应用程序的所有Android用户发送推送消息。我只能发送给一个用户,无法发送给所有用户。

这是我的代码:

PUSH.php

<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'my api key');

$registrationIds = array( 'user_push_id');


$msg = array
(
    'URL'   => 'http://www.apple.com/in/',
    'message'   => 'Did you like it ???',
    'image' =>'http://icons.iconarchive.com/icons/dan-wiersma/apple-tv/128/Apple-Logo-icon.png'
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'          => $msg
);

$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 );
echo $result;
?>

请帮我从mysql表中获取所有用户,如下所示:

$sth = mysqli_query("SELECT PUSH_ME from push_msg_android");
$registrationIds = array();
while($r = mysqli_fetch_array($sth)) {
    $registrationIds['PUSH_ID'] = $r;
}

1 个答案:

答案 0 :(得分:1)

要向多个用户发送推送通知,您需要向所有用户填写registrationIds数组&#39;注册ID。

最后,如果你有3个用户,它应该是这样的:

[78475826748590, 74648598273895, 85737485957849]

在您的情况下,这意味着替换此行:

$registrationIds = array( 'user_push_id');

由:

$result = mysqli_query($db, "SELECT PUSH_ID from push");
$registrationIds = array();
while($row = mysqli_fetch_array($result)) {
   $registrationIds[] = $row[0];
}

这假设您的用户注册ID存储在数据库表PUSH_ID的{​​{1}}列中。

在更正常的设置中,您的用户所在的位置注册ID将存储在表push中的push_notification_id列中,查询应为:

users

您之前还需要创建$result = mysqli_query($db, "SELECT push_notification_id from users"); $registrationIds = array(); while($row = mysqli_fetch_array($result)) { $registrationIds[] = $row[0]; } 对象,以创建与数据库的连接。例如:

$db
相关问题