>我已经看过许多使用 php 和 mysql 向 Android 设备发送推送通知的教程,但我想使用 PDO 来实现这一点,我一直在试图找出问题,我得到"无效注册",但如果我直接将 GCM 注册 ID 分配给变量,它就可以工作,但如果我从数据库中获取 GCM 注册 ID,它就不起作用。我认为问题在于从PDO获得的数组结构
这是我得到的错误
{"multicast_id":5263664448936997879,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
当我回显我正在发送的数组时
Array ( [registration_ids] => Array ( [0] => Array ( [gcm_id] => APA91bGZs7DIb2lVvtlx-Ltgz2_wbRcMIvy-MfYPxoXt6SyDQlUjEnxgNTEw2vS6U5fe9u62i1LZo_gfhipUqT-FCgDj0U7JAwWwOvVmEhx9xIcs0k6mBsg7AgY6pxCVuaXYhqde0mZd ) ) ) [data] => Array ( [update] => thbtrhrt ) )
我的代码是
function send_notification($registatoin_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
print_r($fields);
$headers = array(
'Authorization: key=AShthdfDeac36l6c6G1huGogerJDUvtvOPQ6hA',
'Content-Type: application/json'
);
$ch = curl_init();
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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
function getGCMIds($univid)
{
global $dbConnect;
$query = $dbConnect->prepare("SELECT gcmid FROM android_gcm_table WHERE univid = ?");
$query->bindValue(1, $univid);
$query->execute();
try
{
return $results = $query->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
$gcmIds = getGCMIds($_POST['univ']); // if i directly paste the gcm reg id here and put $gcmIds in array then its working.
$notification = $_POST['message'];
$notification = array("update" => $notification);
echo $resultLast = send_notification($gcmIds, $notification);
如果有人帮助我就太好了,谢谢
$query->fetchAll(PDO::FETCH_COLUMN) 为我工作
function getGCMIds($univid)
{
global $dbConnect;
$query = $dbConnect->prepare("SELECT gcmid FROM android_gcm_table WHERE univid = ?");
$query->bindValue(1, $univid);
$query->execute();
try
{
return $results = $query->fetchAll(PDO::FETCH_COLUMN);
}
catch(PDOException $e)
{
die($e->getMessage());
}
}