PHP Push Notifications cho iOS và Android

Thảo luận trong 'PHP' bắt đầu bởi xman, 20/1/16.

  1. xman

    xman Administrator Thành viên BQT

    Tham gia ngày:
    6/7/15
    Bài viết:
    43
    Đã được thích:
    2
    Điểm thành tích:
    8
    PHP:
    <?php

    class PushNotification
    {
        protected 
    $sandbox false;

        protected 
    $ios_pem_file_path "";

        protected 
    $google_api_key "";

        public function 
    ios($device_token$message null, array $args = array())
        {
            if(!
    $device_token)
            {
                return;
            }

            
    $ctx stream_context_create();
            
    stream_context_set_option($ctx'ssl''local_cert'$this->ios_pem_file_path);
            
    stream_context_set_option($ctx'ssl''passphrase''pushchat');
            
    $sandbox $this->sandbox 'sandbox.' '';
            
    $url "ssl://gateway.{$sandbox}push.apple.com:2195";
            
    $fp stream_socket_client($url$err$errstr60STREAM_CLIENT_ASYNC_CONNECT$ctx);
            if (!
    $fp){
                return 
    false;
            }

            
    //$body['aps'] = ['badge' => 5, 'content-available' => 1];
            
    $body['aps'] = $args+['sound' => 'default''alert' => $message];
            
    $payload json_encode($body);
            
    $msg chr) . pack('n'32) . pack('H*'$device_token) . pack('n'strlen($payload)) . $payload;
            
    fwrite($fp$msgstrlen($msg));
            
    fclose($fp);
            return 
    true;
        }

        public function 
    android($device_token$message null, array $args = array())
        {
            if(!
    $device_token)
            {
                return 
    false;
            }

            
    $ch curl_init('https://android.googleapis.com/gcm/send');
            
    curl_setopt($chCURLOPT_POSTtrue);
            
    curl_setopt($chCURLOPT_TIMEOUT1);
            
    curl_setopt($chCURLOPT_HTTPHEADER, array(
                
    'Authorization: key='.$this->google_api_key,
                
    'Content-Type: application/json'
            
    ));
            
    curl_setopt($chCURLOPT_RETURNTRANSFERTRUE);
            
    curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);
            
    curl_setopt($chCURLOPT_POSTFIELDSjson_encode(array(
                
    'registration_ids' => array($device_token),
                
    'data' => $args+['sound' => 'default''alert' => $message],
            )));
            
    $result curl_exec($ch);
            
    curl_close($ch);
            return 
    $result;
        }


    }
    ?> 
    Nguồn: http://www.phpclasses.org/package/9547-PHP-Send-push-notifications-for-iOS-or-Android-devices.html
     

Chia sẻ trang này