普通网友 2016-05-10 09:57
浏览 83
已采纳

结合ios(推送通知)和android(GCM)API(Web服务)进行通知

I am a android developer so i don't know that much about PHP.

we are developing exam paper app in Android and IOS. and create notification functionality its works perfectly. But problem is IOS use Push notification and android use GCM. And these two are use different api.

My question is how to combine these two api. I want to combine this two api (webservice) in one. When admin upload paper then all user get notify using notification weather it is android or IOS device.

What should i do? Help much appreciate thanks in advance. i am using this LINK

Here is my effort

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 . "
";
      fwrite($fp, $msg);
      fclose($fp);
?>

Is it possible or not?? if any suggestion or other way to get this done please tell me.

  • 写回答

4条回答 默认 最新

  • dongrou5254 2016-05-11 08:25
    关注

    I Found the solution in github And it's for Android , IOS and windows.
    Thanks to joashp.

    use this two file.

    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("
    ", $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 
    
    }
    ?>
    

    And it's work perfect. just use your database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?