【问题标题】:Combine ios (Push notification) and android (GCM) API (webservice) for notification结合 ios (Push notification) 和 android (GCM) API (webservice) 进行通知
【发布时间】:2016-05-10 09:57:03
【问题描述】:

我是一名 Android 开发人员,所以我对 PHP 了解不多。

我们正在开发 Android 和 IOS 的试卷应用程序。并创建完美的通知功能。但问题是 IOS 使用推送通知而 android 使用 GCM。这两个使用不同的api。

我的问题是如何结合这两个 api。我想将这两个 api (webservice) 合二为一。当管理员上传文件时,所有用户都会使用通知天气收到通知,它是 android 或 IOS 设备。

我该怎么办?帮助非常感谢提前感谢。我正在使用这个 LINK

这是我的努力

Android API

 <?php

require_once('connect.php');
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'AIzaSyBWcc6ONXvNEHECxzLwFDSDCTKDTjEhfT8' );
//$registrationIds = array( $_GET['id'] );

$conn = new mysqli('host name', 'server name', 'password', 'database name');

    $select_qury = "SELECT gcm_registration_id FROM gtu_registration";
    $result = $conn->query($select_qury);

$registrationIds = array();

while($row = $result->fetch_assoc()){

    array_push($registrationIds, $row['gcm_registration_id']);
}
// prep the bundle
$msg = array
(
    'message'   => 'here is a message. message',
    'title'     => 'This is a title. title',
    'subtitle'  => 'This is a subtitle. subtitle',
    'tickerText'=> 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
);

//Creating a new array fileds and adding the msg array and registration token array here 
$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'          => $msg
);

 //Adding the api key in one more array header 
$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 );

//Decoding json from result 
    $res = json_decode($result);

    $flag = $res->success;

    //if success is 1 means message is sent 
    if($flag == 1){
        //Redirecting back to our form with a request success 
        header('Location: index.php?success');
    }else{
        //Redirecting back to our form with a request failure 
        header('Location: index.php?failure');
    }

echo $result;

IOS API

<?php
      $token ='f1088d1c0603218b31b5a26210c4b0e60e4884225235c7f5c2e55c47b937a03d';
      $deviceToken = $token; // token dell'iPhone a cui inviare la notifica

      // Passphrase for the private key (ck.pem file)
       $pass = "mac12345";
      // Get the parameters from http get or from command line
      $message = 'Notification text';
      $badge = 1;
      $sound = 'default';

      // Construct the notification payload
      $body = array();
      $body['aps'] = array('alert' => $message);

      if ($badge)
            $body['aps']['badge'] = $badge;
      if ($sound)
            $body['aps']['sound'] = $sound;

      / End of Configurable Items /
      $ctx = stream_context_create();
      stream_context_set_option($ctx, 'ssl','local_cert', 'Gtuck.pem');

      // assume the private key passphase was removed.
      stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
      $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 120, STREAM_CLIENT_CONNECT, $ctx);


      $payload = json_encode($body);
      $msg = chr(0).pack('n',32).pack('H*', str_replace(' ', '', $deviceToken)).pack('n',strlen($payload)).$payload;
      print "" . $payload . "\n";
      fwrite($fp, $msg);
      fclose($fp);
?>

有没有可能??如果有任何建议或其他方式来完成这项工作,请告诉我。

【问题讨论】:

    标签: php android ios web-services notifications


    【解决方案1】:

    以下代码由我使用,您可以根据自己的方式更改

    根据设备操作系统

    if($gcm_id_array['os'] == 'android')
                {
        $v[$index] = scs_single_gcm($gcm_id_array['gcm_id'],$message);
                    $index++;
                }else{
                    $v[$index] = scs_single_gcm_ios($gcm_id_array['gcm_id'],$message);
                    $index++;
                }
    

    ios函数scs_single_gcm_ios

    function  scs_single_gcm_ios($regids,$message)
        {
            try{
            $deviceToken = $regids;
            $passphrase = 'Kookdokoo';
            $title = $message['title'];
            $id = $message['noti_id'];
    
            $ctx = stream_context_create();
            stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
            stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
    
            $fp = stream_socket_client(
                'ssl://gateway.push.apple.com:2195', $err,
                $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
    
            if (!$fp)
                exit("Failed to connect: $err $errstr" . PHP_EOL);
    
    
            $body['aps'] = array(
                'alert' => $title,
                'sound' => 'default',
                'id' =>$id
                );
    
            // Encode the payload as JSON
            $payload = json_encode($body);
    
            // Build the binary notification
    
            $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
    
            // Send it to the server
            $result = fwrite($fp, $msg, strlen($msg));
    
            if (!$result)
                $result = 0;
            else
                $result = 1;
    
            // Close the connection to the server
            fclose($fp);
            return $result;
            }
            catch(Exception $e){
              $e->getMessage();
                }
        }
    

    安卓版

    function scs_single_gcm($regids,$message)
    {
    
    
        if(is_array($regids)){
            $fields = array(
                    'registration_ids'  =>  $regids,
                    'data'              => array( "data" => $message ),
                    );
    
        }else
        {   
            $fields = array(
                    'registration_ids'  =>  array($regids),
                    'data'              => array( "data" => $message ),
                    );
    
        }
        // Open connection
        $ch = curl_init();
         if (FALSE === $ch)
            throw new Exception('failed to initialize');
        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, 3);
        curl_setopt( $ch, CURLOPT_URL,url );
        curl_setopt( $ch, CURLOPT_POST, true );
        curl_setopt( $ch, CURLOPT_HTTPHEADER,array(key,content_type));
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
        // Execute post
        $result = curl_exec($ch);   
        /*
        if (FALSE === $result)
            echo curl_error($ch).curl_errno($ch);
        // Close connection
        curl_close($ch);
        if (curl_errno( $ch ) ){
            'GCM error: ' . curl_error( $ch );
            }
        */  
        $result = json_decode($result);
    
           $notification = 1;
           if($result->success){
                $nm = 'push notification success';
                   $p = 1;
           }else{
                  if($result->results[0]->error == "NotRegistered")
                  {
          $nm = 'push notification success';
                  $p = 1;
                  }else{
                    $nm = 'push notification failed';
                  $p = 0;
                  }
    
           }
    

    【讨论】:

      【解决方案2】:

      我认为这里没有问题。您需要设计一种推送令牌存储。此存储的每条记录将包含有关用户设备的信息:push_token(或 gcm_registration_id,如果它是 android 设备)、平台类型(iOS/android),如果您有一些帐户系统,可能还有 user_id。当您获取此表时,您会根据平台属性的值调用相关函数(我们将它们命名为 send_ios_push($token, $msg)send_android_push($reg_id, $msg))。

      【讨论】:

      • 我不知道你目前的架构。这两个代码sn-ps已经足够实现单独的推送发送了,你只需要将它们封装成单独的php函数,根据设备平台调用即可。你熟悉php吗?
      • 在你的数据库中,你需要添加一些标志,比如用户是安卓设备还是iOS设备,根据这个你可以设置你的脚本
      • 你有任何链接或示例@DigantShah ??
      【解决方案3】:
          //ios push notification script
          // database query
      if(yourdevice == 'ios')
      {
          $ctx = stream_context_create();
          stream_context_set_option($ctx, 'ssl', 'cafile', 'entrust_2048_ca.cer');
          stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
          stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
      
          // Open a connection to the APNS server
          $fp = stream_socket_client(
              'ssl://gateway.sandbox.push.apple.com:2195', $err,
              $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
      
          if (!$fp)
              exit("Failed to connect: $err $errstr" . PHP_EOL);
      
          echo 'Connected to APNS' . PHP_EOL;
      
          // Create the payload body
          $body['aps'] = array(
              'alert' => $message,
              'sound' => 'incoming123.wav'
              );
      
          // Encode the payload as JSON
          $payload = json_encode($body);
      
          // Build the binary notification
          $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
      
          // Send it to the server
          $result = fwrite($fp, $msg, strlen($msg));
      
          if (!$result)
              echo 'Message not delivered' . PHP_EOL;
          else
              echo 'Message successfully delivered' . PHP_EOL;
      
          // Close the connection to the server
          fclose($fp);
         } else { 
      
          //Android Notification
      
          define( 'API_ACCESS_KEY', 'AIzaSyBWcc6ONXvNEHECxzLwFDSDCTKDTjEhfT8' );
          //$registrationIds = array( $_GET['id'] );
      
          $conn = new mysqli('host name', 'server name', 'password', 'database name');
      
              $select_qury = "SELECT gcm_registration_id FROM gtu_registration";
              $result = $conn->query($select_qury);
      
          $registrationIds = array();
      
          while($row = $result->fetch_assoc()){
      
              array_push($registrationIds, $row['gcm_registration_id']);
          }
          // prep the bundle
          $msg = array
          (
              'message'   => 'here is a message. message',
              'title'     => 'This is a title. title',
              'subtitle'  => 'This is a subtitle. subtitle',
              'tickerText'=> 'Ticker text here...Ticker text here...Ticker text here',
              'vibrate'   => 1,
              'sound'     => 1,
              'largeIcon' => 'large_icon',
              'smallIcon' => 'small_icon'
          );
      
          //Creating a new array fileds and adding the msg array and registration token array here 
          $fields = array
          (
              'registration_ids'  => $registrationIds,
              'data'          => $msg
          );
      
           //Adding the api key in one more array header 
          $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 );
      
          //Decoding json from result 
              $res = json_decode($result);
      
              $flag = $res->success;
      
              //if success is 1 means message is sent 
              if($flag == 1){
                  //Redirecting back to our form with a request success 
                  header('Location: index.php?success');
              }else{
                  //Redirecting back to our form with a request failure 
                  header('Location: index.php?failure');
              }
      
          echo $result;
      }
      

      【讨论】:

      • 我会尽力让你知道
      • 但这是 if else 条件。我想同时运行
      • @Digant Shah 在这里你的答案与你添加的问题相同如果条件。所以尝试简要解释一下。bcs ios 代码是通过静态令牌 id
      【解决方案4】:

      我在 github 中找到了解决方案 它适用于 AndroidIOSwindows
      感谢 joashp。

      使用这两个文件。

      test.php

      <?php
      include_once('connect.php');
      require_once('notification.php');
      
      $device_type = $_GET['device_type'];
      
      $sql = "SELECT gcm_registration_id from gtu_registration where device_type = 'Android'";
      
      $result = mysqli_query($con, $sql);
      
      while($row = mysqli_fetch_array($result))
      
      {
      
          // $output[] = $row;
      
      
            // $message = $row['message'];    
              $gcm_registration = $row['gcm_registration_id'];
      
           // print(json_encode($gcm_registration));
            //print(json_encode($gcm_registration));
      
      }   
      
      $sql = "SELECT title ,message from gtu_message";
      $result = mysqli_query($con, $sql);
      
      while($row = mysqli_fetch_array($result))
      
      {
      
          // $output[] = $row;
      
      
              $title = $row['title']; 
              $message = $row['message'];
      
           // print(json_encode($gcm_registration));
            //print(json_encode($gcm_registration));
      
      }   
      $msg_payload = array (
              'mtitle' => $title,
              'mdesc' => $message,
          );  
      
      
          PushNotifications::android($msg_payload, $gcm_registration);
          //echo 'Success';
      
      
          if(!$gcm_registration)
          {
      
              echo 'Failure';
          }else
          {
              echo 'Android Success';
          }
      
      $query = "select * from gtu_registration where device_type = 'IOS'";
      $results = mysqli_query($con, $query);
      
      while($rows = mysqli_fetch_array($results))
      
      {
      
      
            $gcm_registrations = $rows['gcm_registration_id'];
      
      
      }   
      $sql = "SELECT title ,message from gtu_message";
      $result = mysqli_query($con, $sql);
      
      while($row = mysqli_fetch_array($result))
      
      {
      
          // $output[] = $row;
      
      
            // $message = $row['message'];    
              $message = $row['message'];
              $title = $row['title'];
      
           // print(json_encode($gcm_registration));
            //print(json_encode($gcm_registration));
      
      }       
          $msg_payload = array (
              'mtitle' => $title,
              'mdesc' => $message,
          );      
      
          PushNotifications::iOS($msg_payload, $gcm_registrations);
      
      if(!$gcm_registrations)
      {
      
          echo 'Failure';
      
      }   else {
      
          echo 'IOS Success';
      }
      
      ?>
      

      notification.php

      <?php 
      // Server file
      class PushNotifications {
          // (Android)API access key from Google API's Console.
          private static $API_ACCESS_KEY = 'AIzaSyBWcc6ONXvNEHECxzLwFDSDCTKDTjEhfT8';
          // (iOS) Private key's passphrase.
          private static $passphrase = 'mac12345';
          // (Windows Phone 8) The name of our push channel.
      
      
          // Change the above three vriables as per your app.
          public function __construct() {
              exit('Init function is not allowed');
          }
      
              // Sends Push notification for Android users
          public function android($data, $reg_id) {
                  $url = 'https://android.googleapis.com/gcm/send';
                  $message = array(
                      'title' => $data['mtitle'],
                      'message' => $data['mdesc'],
                      'subtitle' => '',
                      'tickerText' => '',
                      'msgcnt' => 1,
                      'vibrate' => 1
                  );
      
                  $headers = array(
                      'Authorization: key=' .self::$API_ACCESS_KEY,
                      'Content-Type: application/json'
                  );
      
                  $fields = array(
                      'registration_ids' => array($reg_id),
                      'data' => $message,
                  );
          self::useCurl($url, $headers, json_encode($fields)); 
      
              }
      
          // Sends Push's toast notification for Windows Phone 8 users
          public function WP($data, $uri) {
              $delay = 2;
              $msg =  "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
                      "<wp:Notification xmlns:wp=\"WPNotification\">" .
                          "<wp:Toast>" .
                              "<wp:Text1>".htmlspecialchars($data['mtitle'])."</wp:Text1>" .
                              "<wp:Text2>".htmlspecialchars($data['mdesc'])."</wp:Text2>" .
                          "</wp:Toast>" .
                      "</wp:Notification>";
      
              $sendedheaders =  array(
                  'Content-Type: text/xml',
                  'Accept: application/*',
                  'X-WindowsPhone-Target: toast',
                  "X-NotificationClass: $delay"
              );
      
              $response = $this->useCurl($uri, $sendedheaders, $msg);
      
              $result = array();
              foreach(explode("\n", $response) as $line) {
                  $tab = explode(":", $line, 2);
                  if (count($tab) == 2)
                      $result[$tab[0]] = trim($tab[1]);
              }
      
              return $result;
          }
      
              // Sends Push notification for iOS users
          public function iOS($data, $devicetoken) {
              $deviceToken = $devicetoken;
              $ctx = stream_context_create();
              // ck.pem is your certificate file
              stream_context_set_option($ctx, 'ssl', 'local_cert', 'Gtuck.pem');
              stream_context_set_option($ctx, 'ssl', 'passphrase', self::$passphrase);
              // Open a connection to the APNS server
              $fp = stream_socket_client(
                  'ssl://gateway.sandbox.push.apple.com:2195', $err,
                  $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
              if (!$fp)
                  exit("Failed to connect: $err $errstr" . PHP_EOL);
              // Create the payload body
              $body['aps'] = array(
                  'alert' => array(
                      'title' => $data['mtitle'],
                      'body' => $data['mdesc'],
                   ),
                  'sound' => 'default'
              );
              // Encode the payload as JSON
              $payload = json_encode($body);
              // Build the binary notification
              $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
              // Send it to the server
              $result = fwrite($fp, $msg, strlen($msg));
      
              // Close the connection to the server
              fclose($fp);
              if (!$result)
                  return 'Message not delivered' . PHP_EOL;
              else
                  return 'Message successfully delivered' . PHP_EOL;
          }
          private function useCurl( $url, $headers, $fields = null) {
                  // Open connection
                  $ch = curl_init();
                  if ($url) {
                      // 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);
      
                      // Disabling SSL Certificate support temporarly
                      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                      if ($fields) {
                          curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
                      }
      
                      // Execute post
                      $result = curl_exec($ch);
                      if ($result === FALSE) {
                          die('Curl failed: ' . curl_error($ch));
                      }
      
                      // Close connection
                      curl_close($ch);
      
                      return $result;
              }
          }
      
          // Curl 
      
      }
      ?>
      

      而且它工作完美。只需使用您的数据库。

      【讨论】:

      • 密码是什么?我怎样才能知道?
      • 私有静态 $passphrase = 'mac12345'; // 我怎样才能知道?
      • // (iOS) 私钥的密码。
      • 不知道兄弟我是android开发者所以我不知道php但你可以在这个链接gist.github.com/joashp/b2f6c7e24127f2798eb2问因为它是atualy源
      猜你喜欢
      • 2021-07-04
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多