繁体   English   中英

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

[英]How can I send push notification to all users in an array in php?

当我使用 {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);
?>

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

$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 );
}

使用 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);
        }
    }

您可以使用此方法使用以下代码向多个用户发送通知。 下面的代码帮助您发送Firebase 推送通知 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM