PHP:使用firebase向不同的设备发送多个推送通知

时间:2017-12-14 12:27:58

标签: php firebase google-cloud-messaging

我正在尝试使用php将推送通知发送到多个设备。以下是我的代码

(run! println citrus-list)

但是以下是我得到的结果。

define( 'API_ACCESS_KEY', 'mykey');
     $message =' some message ' ; 
     $msg = array
          (
            'body'  =>$message,
            'title' => 'You have a new message ',

          );
          $regids =  array( 'registration_ids' =>'firstid');
    $fields = array
            (
                'to'            =>  json_encode($regids), 

                'notification'  => $msg
            );

    $headers = array
            (
                'Authorization: key=' . API_ACCESS_KEY,
                'Content-Type: application/json'
            );
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/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 );
        echo $result;
        curl_close( $ch );

请帮我解决这个问题

1 个答案:

答案 0 :(得分:0)

将设备ID放入此阵列

$dv_id [] = array(
                'dv_id' => $re['dv_id'],
            );
//Loop through your id's array

for ($i = 1; $i < count($dv_id); $i++) {

//Call your send notification function link this
    send_notification($dv_id[$i]['dv_id'],$title,$msg);
}

function send_notification($device_id,$title,$message){

// API access key from Google API's Console
// prep the bundle
    $msg = array
    (
        'to'=>$device_id,
        'notification' => array('body'=>$message,'title'=>$title,
            'click_action'=>'MY_ACTIVITY_1','sound'=>'tone'),
        'data' => array('message'=>$message,'title'=>$title)

    );
    $headers = array
    (
        'Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL,'https://fcm.googleapis.com/fcm/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( $msg ) );
    $result = curl_exec($ch );
    curl_close( $ch );

}

快乐编码。