如何在PHP数组中向所有用户发送推送通知?

时间:2019-11-22 11:16:00

标签: php android firebase curl firebase-cloud-messaging

当我使用{select token FROM riders}时,我想以这种方式选择所有令牌并将推式通知发送给所有令牌,但是当我这样做时,它不发送任何通知。

<?php


define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'android_api');

//connecting to database and getting the connection object
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

$stmt = mysqli_query($conn,"SELECT token FROM riders");
$query = mysqli_fetch_array($stmt);

$token = $query['token'];


$apiKey = "AAAAKCR7bo4:APA91bHuIwpxHkR5VxODbqje6b518xbBLWUnVfucuUJNJzqzTYDyww-   dwkPtgUj.........aDWTNyfARF0ru16"; //Server Key Legacy
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';


$notification = array('title' =>'iDELIVERY',
                   'body' => 'A Request Has Been Made');

$notifdata = array('title' =>'test title data',
                 'body' => 'hello',
                 'image' => 'path'
          );

$fcmNotification = array (
                    'to'        => $token, 
                    'notification' => $notification,
                    'data' => $notifdata 
                );


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

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,$fcmUrl);
            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($fcmNotification));
            $result = curl_exec($ch);
          //  curl_close($ch);
?>

3 个答案:

答案 0 :(得分:1)

使用PHP

   function sendNotifiation(){

      define('DB_HOST', 'localhost');
      define('DB_USER', 'root');
      define('DB_PASS', '');
      define('DB_NAME', 'android_api');

      //connecting to database and getting the connection object
      $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);


      $stmt = mysqli_query($conn,"SELECT token FROM riders");
      $query = mysqli_fetch_array($stmt);

      $token = $query['token'];
      $title = "Your notification title";
      $body = "Your notification body";
      $message = "Your notification message";

      sendAndroidNotification($token, $message,$title,$body);    
    }

    function sendAndroidNotification($device_token, $message = null,$title,$body) {

      if (!empty($device_token) && $device_token != 'NULL') {

          $device_token = json_decode(json_encode($device_token));

          $FIREBASE_API_KEY = 'key';
          $url = 'https://fcm.googleapis.com/fcm/send';
          $notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
          $fields = array('registration_ids' => $device_token, 'notification' => $notification,'priority'=>'high','data' => $message);

          $headers = array(
          'Authorization: key=' .$FIREBASE_API_KEY,
          '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));

          // Execute post
          $result = curl_exec($ch);

          // Close connection
          curl_close($ch);
        }
    }

答案 1 :(得分:1)

我正在发送一个在我的移动应用程序中使用过的工作代码,您应该根据您的数据集获取多个令牌,示例代码如下所示

$stmt = mysqli_query($conn,"SELECT token FROM riders where phone='026'");

//Itrate token and store it in an array based on your dataset
$allTokens = array();
foreach($tokens as $token){
    $allTokens[] = $token['token'];
}

 // This is a sample KEY
define( 'API_ACCESS_KEY', 'AIdsdyALOdsds7pR01rydsds0dsdqQndsdsOVpPpy4adsds');

// Build your message as an array
$msg = array( 
            'title'         => "Payment Alert",
            'message'       => "You have received a test payment",
            'bigText'       => "You have received a test payment",
            "subText"       => "You have received a test payment",
            'summaryText'   => 'Alert for payment',
            'click_action'  => 'FCM_PLUGIN_ACTIVITY',
            'vibrate'       => 300,
            'sound'         => 1,
);
$fields = array(
'registration_ids'  => $allTokens,  // multiple tokens will be available in array
'data'              => $msg
);
$headers = array(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
if(!empty($allTokens)){
    $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 );
    curl_close( $ch );
}

答案 2 :(得分:0)

您可以使用以下方法使用此方法向多个用户发送通知。以下代码可帮助您发送Firebase push notification android

<?php
$target = ["TARGET_ID"];

$notificationBody['data'] = [
    'type' => 1,
    'url' => "https://trinitytuts.com/wp-content/uploads/2018/07/macaw.png",
    'title' => "title",
    "msg" => "Message"
];

$response = sendMessage($notificationBody, $target, $_POST['serverKey']);

function sendMessage($data, $target, $serverKey){
    //FCM api URL
    $rsp = [];
    $url = 'https://fcm.googleapis.com/fcm/send';
    //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
    $server_key = $serverKey;
    $fields = array();
    $fields['data'] = $data;
    if(is_array($target)){
            $fields['registration_ids'] = $target;
        }else{
            $fields['to'] = $target;
    }
    //header with content_type api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization:key='.$server_key
    );

    $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('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);

    //print_r($result);
    return $result;
}