2016-11-17 113 views
1

我正在向用户发送消息。该消息已成功发送。但我不是在android手机上收到通知。我有代码: -在android中使用php发送推送通知使用php

enter code here 
public function send_android_notification($device,$message,$user,$sender_id,$reciever_id,$list_id,$username) 
{ 
     define('API_ACCESS_KEY', 'My key(i already embed)'); 
     $registrationIds = array($device); 
     // prep the bundle 
     $msg = array 
     (
     'message' => $message['Message']['message'], 
     'user'=>$user, 
     'sender_id' =>$sender_id, 
     'reciever_id' =>$reciever_id, 
     'list_id'=>$list_id, 
     'username' =>$username 
     ); 
     $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; 
    } 

任何人都可以帮助我。余吨给我输出: - enter image description here

{ “multicast_id”:8119665273981115453, “成功”:0, “失败”:1, “canonical_ids”:0

+0

失败'InvalidRegistration',不成功。看文档了解错误:https://developers.google.com/cloud-messaging/http-server-ref#table8 –

+0

我不明白会发生什么。该消息已成功发送但未收到通知。请帮忙! – kunal

+0

“success”:0,“failure”:1 –

回答

2
?php 
function sendPushNotificationToGCM($device, $message,$user,$sender_id,$reciever_id,$list_id,$username) { 
     //Google cloud messaging GCM-API url 
     $url = 'https://android.googleapis.com/gcm/send'; 
     $fields = array(
      'registration_ids' => $device, 
      'data' => $msg = array (
        'message' => $message['Message']['message'], 
        'user'=>$user, 
        'sender_id' =>$sender_id, 
        'reciever_id' =>$reciever_id, 
        'list_id'=>$list_id, 
        'username' =>$username 
       ), 
     ); 

     $headers = array(
      'Authorization: key=youKey', 
      '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_VERIFYHOST, 0); 
     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; 
    } ?> 

请试试这个。这在我的情况下工作。请尝试。并且检查你的设备ID是否正确。

+0

不工作paranav – kunal

+0

它在我的应用程序中工作完美... –

+0

请参阅http://stackoverflow.com/questions/11242743/ gcm-with-php-google-cloud-messaging –