コード例 #1
3
ファイル: util.php プロジェクト: 0x7678/activeMDM
function send_push($device)
{
    $deviceToken = unpack('H*', base64_decode($device["deviceToken"]));
    $deviceToken = $deviceToken[1];
    date_default_timezone_set('Europe/London');
    $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, '/home/jimbob/final_aps_prod.pem');
    $push->setProviderCertificatePassphrase('FunCrate321');
    $push->connect();
    $message = new ApnsPHP_Message($deviceToken);
    // Set a custom property
    $message->setCustomProperty('mdm', $device['pushMagic']);
    // Set the expiry value to 30 seconds
    $message->setExpiry(30);
    $push->add($message);
    var_dump($message->getPayload());
    // Send all messages in the message queue
    $push->send();
    // Disconnect from the Apple Push Notification Service
    $push->disconnect();
    // Examine the error message container
    $aErrorQueue = $push->getErrors();
    if (!empty($aErrorQueue)) {
        var_dump($aErrorQueue);
    }
}
コード例 #2
0
ファイル: Device.php プロジェクト: AndreyTepaykin/Platform
 /**
  * Adds a device to the system, after sending a test notification to it
  * @param {array} $device
  * @param {string} $device.userId
  * @param {string} $device.deviceId
  * @param {string} [$device.formFactor]
  * @param {string} [$device.platform]
  * @param {string} [$device.version]
  * @param {string} [$device.sessionId]
  * @param {boolean} [$device.sandbox]
  * @param {string} [$device.passphrase]
  * @param {boolean} [$skipNotification=false] if true, skips sending notification
  * @return {Users_Device}
  */
 static function add($device, $skipNotification = false)
 {
     Q_Valid::requireFields(array('userId', 'deviceId'), $device, true);
     $userId = $device['userId'];
     $deviceId = $device['deviceId'];
     if (!$skipNotification) {
         $app = Q::app();
         $sandbox = Q::ifset($device, 'sandbox', null);
         if (!isset($sandbox)) {
             $sandbox = Q_Config::get($app, "cordova", "ios", "sandbox", false);
         }
         $env = $sandbox ? ApnsPHP_Abstract::ENVIRONMENT_SANDBOX : ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION;
         $s = $sandbox ? 'sandbox' : 'production';
         $cert = APP_LOCAL_DIR . DS . 'Users' . DS . 'certs' . DS . $app . DS . $s . DS . 'bundle.pem';
         $authority = USERS_PLUGIN_FILES_DIR . DS . 'Users' . DS . 'certs' . DS . 'EntrustRootCA.pem';
         $logger = new Users_ApnsPHP_Logger();
         $push = new ApnsPHP_Push($env, $cert);
         $push->setLogger($logger);
         $push->setRootCertificationAuthority($authority);
         if (isset($device['passphrase'])) {
             $push->setProviderCertificatePassphrase($device['passphrase']);
         }
         $push->connect();
         $message = new ApnsPHP_Message($deviceId);
         $message->setCustomIdentifier('Users_Device-adding');
         $message->setBadge(0);
         $message->setText(Q_Config::get($app, "cordova", "ios", "device", "text", "Notifications have been enabled"));
         $message->setCustomProperty('userId', $userId);
         $message->setExpiry(5);
         $push->add($message);
         $push->send();
         $push->disconnect();
         $errors = $push->getErrors();
         if (!empty($errors)) {
             $result = reset($errors);
             throw new Users_Exception_DeviceNotification($result['ERRORS'][0]);
         }
     }
     $sessionId = Q_Session::id();
     $user = Users::loggedInUser();
     $info = array_merge(Q_Request::userAgentInfo(), array('sessionId' => $sessionId, 'userId' => $user ? $user->id : null, 'deviceId' => null));
     $device2 = Q::take($device, $info);
     $d = new Users_Device($device2);
     $d->save(true);
     if ($sessionId) {
         $s = new Users_Session();
         $s->id = $sessionId;
         if (!$s->retrieve()) {
             $s->deviceId = $deviceId;
         }
     }
     $_SESSION['Users']['deviceId'] = $deviceId;
     $device2['Q/method'] = 'Users/device';
     Q_Utils::sendToNode($device2);
     return $d;
 }
コード例 #3
0
 function sendNotificationByApns($deviceToken, $msg, $type, $userId)
 {
     $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, 'certificate/aps_dist_certi.pem');
     $push->setRootCertificationAuthority('certificate/aps_dist_certi.pem');
     $push->connect();
     $message = new ApnsPHP_Message($deviceToken);
     //        $message = new ApnsPHP_Message("407fa2549e4cb290c4f13059340a36e69679d9e1ba34b40751663819d98281ab");
     $message->setCustomProperty('type', $type);
     $message->setCustomProperty('userId', $userId);
     //        $message->setCustomProperty('channelName',$channelName);
     $message->setText($msg);
     $message->setBadge(1);
     $message->setSound();
     $push->add($message);
     $res = $push->send();
     $push->disconnect();
     //        return true;
     //            echo "sese";
     //            exit;
 }
コード例 #4
0
// Connect to the Apple Push Notification Service
$push->connect();
// Instantiate a new Message with a single recipient
//$message = new ApnsPHP_Message('1e82db91c7ceddd72bf33d74ae052ac9c84a065b35148ac401388843106a7485');
$message = new ApnsPHP_Message('5fd4e4af4aec6b1e61b3d3c1d1165151ac3bfa29ef362bfdb482b3acf7ecea6a');
// Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
// over a ApnsPHP_Message object retrieved with the getErrors() message.
$message->setCustomIdentifier("Message-Badge-3");
// Set badge icon to "3"
$message->setBadge(3);
// Set a simple welcome text
$message->setText('COULD YOU COME DOWN FOR THE PROJECT MEETING?!');
// Play the default sound
$message->setSound();
// Set a custom property
$message->setCustomProperty('acme2', array('bang', 'whiz'));
// Set another custom property
$message->setCustomProperty('acme3', array('bing', 'bong'));
// Set the expiry value to 30 seconds
$message->setExpiry(30);
// Add the message to the message queue
$push->add($message);
// Send all messages in the message queue
$push->send();
// Disconnect from the Apple Push Notification Service
$push->disconnect();
// Examine the error message container
$aErrorQueue = $push->getErrors();
if (!empty($aErrorQueue)) {
    var_dump($aErrorQueue);
}
コード例 #5
0
date_default_timezone_set('Asia/Tokyo');
error_reporting(-1);
//?
require_once 'ApnsPHP/Autoload.php';
$device_token = '2290c9ec028b078755909849a66d1ae2b83ea854eba2880f035395a2bc8c62de';
$url = 'http://kaicyo.local/Hackason/ResisterContents.php';
$text = 'didUpperSwipeAnyone';
$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'push_development.pem');
$push->setRootCertificationAuthority('entrust_root_certification_authority.pem');
$push->connect();
/* コンテンツの送信 */
$message = new ApnsPHP_Message($device_token);
$message->setCustomIdentifier("Message-Badge-3");
//?
$message->setBadge(3);
//?
$message->setText($text);
$message->setSound();
// default sound
// Set a custom property, meta data
$message->setCustomProperty('url', $url);
//$message->setCustomProperty('acme3', array('bing', 'bong'));
$message->setExpiry(30);
// Set the expiry value to 30 seconds
$push->add($message);
$push->send();
$push->disconnect();
$aErrorQueue = $push->getErrors();
if (!empty($aErrorQueue)) {
    var_dump($aErrorQueue);
}
コード例 #6
0
ファイル: Apns.php プロジェクト: garixi/yii2-apns-gcm
 /**
  * send a push notification for ios using APNS client
  *
  * Usage 1:
  * <code>
  * $this->send(
  *  'some-valid-token',
  *  'some-message',
  *  [
  *    'custom_data_key_1'=>'custom_data_value_1',
  *    'custom_data_key_2'=>'custom_data_value_2',
  *  ],
  *  [
  *    'badge'=>2,
  *    'expiry'=>30
  *    'sound'=>'default',
  *  ]
  * );
  * </code>
  * @param string $token
  * @param string $text a message in sending push notification
  * @param array $payloadData The payload contains information about how the system should alert the user as well as any custom data you provide
  * @param array $args optional additional information in sending a message
  * @return ApnsPHP_Message|null
  * @tutorial https://github.com/duccio/ApnsPHP
  */
 public function send($token, $text, $payloadData = [], $args = [])
 {
     // check if its dry run or not
     if ($this->dryRun === true) {
         $this->log($token, $text, $payloadData, $args);
         $this->success = true;
         return null;
     }
     $message = new \ApnsPHP_Message($token);
     $message->setText($text);
     foreach ($args as $method => $value) {
         if (strpos($method, 'set') === false) {
             $method = 'set' . ucfirst($method);
         }
         $value = is_array($value) ? $value : [$value];
         call_user_func_array([$message, $method], $value);
     }
     // set a custom payload data
     foreach ($payloadData as $key => $value) {
         $message->setCustomProperty($key, $value);
     }
     // Add the message to the message queue
     $this->add($message);
     // send a message
     $this->getClient()->send();
     $this->errors = $this->getClient()->getErrors();
     $this->success = empty($this->errors) ? true : false;
     return $message;
 }
コード例 #7
0
ファイル: api.php プロジェクト: bhagwangurav/push2press
 // Connect to the Apple Push Notification Service
 $push->connect();
 // Instantiate a new Message with a single recipient
 $message = new ApnsPHP_Message($msgpusht);
 // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
 // over a ApnsPHP_Message object retrieved with the getErrors() message.
 $message->setCustomIdentifier("Message-Badge-3");
 // Set badge icon to "3"
 $message->setBadge(1);
 // Set a simple welcome text
 $message->setText($notification);
 //$message->setText("test");
 // Play the default sound
 $message->setSound();
 // Set a custom property
 $message->setCustomProperty('msgid', $msgid);
 // Set another custom property
 $message->setCustomProperty('msgdesc', $msgdesc);
 // Set another custom property
 $message->setCustomProperty('sitename', getConfiguration("sitename", ""));
 // Set another custom property
 $message->setCustomProperty('url', getConfiguration("url", ""));
 // Set another custom property
 $message->setCustomProperty('appid', getConfiguration("appid", ""));
 // Set the expiry value to 30 seconds
 $message->setExpiry(30);
 // Add the message to the message queue
 $push->add($message);
 // Send all messages in the message queue
 $push->send();
 // Disconnect from the Apple Push Notification Service
コード例 #8
0
ファイル: IosPush.php プロジェクト: wassafr/push-server
 /**
  * @inheritdoc
  */
 public function sendPush()
 {
     $failedMessages = [];
     if (!isset($this->registrationTokens) || !count($this->registrationTokens)) {
         $failedMessages = $this->registrationTokens;
         return $this->returnResult($failedMessages, $this->registrationTokens);
     }
     // Instanciate a new ApnsPHP_Push object
     $push = new \ApnsPHP_Push($this->parameters['environment'], $this->certificate);
     // Set the Root Certificate Autority to verify the Apple remote peer
     $push->setRootCertificationAuthority($this->parameters['ca_cert']);
     $push->setLogger($this->logger);
     // Connect to the Apple Push Notification Service
     $push->connect();
     foreach ($this->registrationTokens as $index => $token) {
         try {
             $message = new \ApnsPHP_Message($token);
         } catch (\Exception $e) {
             $this->logger->log("ERROR: Device token " . $token . " has problem : " . $e->getMessage());
             $failedMessages[] = $token;
             continue;
         }
         $badge = $this->badges[$index];
         $category = $this->pushData->getApnsCategory();
         $expiry = $this->pushData->getApnsExpiry();
         $text = $this->pushData->getApnsText();
         $sound = $this->pushData->getApnsSound();
         $customProperties = $this->pushData->getApnsCustomProperties();
         $contentAvailable = $this->pushData->getContentAvailable();
         if (!$this->pushData->isSilent()) {
             // DEFAULT PUSH
             if (isset($badge)) {
                 $message->setBadge($badge);
             }
             if (isset($category)) {
                 $message->setCategory($category);
             }
             if (isset($expiry)) {
                 $message->setExpiry($expiry);
             }
             if (isset($text)) {
                 $message->setText($text);
             }
             if (isset($sound)) {
                 $message->setSound($sound);
             } else {
                 $message->setSound();
             }
             if ($contentAvailable) {
                 $message->setContentAvailable(true);
             }
         } else {
             // SILENT PUSH
             $message->setContentAvailable(true);
             // Set push information to custom payload
             if (isset($text)) {
                 $customProperties['alert'] = $text;
             }
             if (isset($category)) {
                 $customProperties['category'] = $category;
             }
         }
         if (isset($customProperties) && is_array($customProperties)) {
             foreach ($customProperties as $name => $value) {
                 $message->setCustomProperty($name, is_scalar($value) ? $value : json_encode($value));
             }
         }
         // Add the message to the message queue
         $push->add($message);
     }
     // Send all messages in the message queue
     try {
         $push->send();
         // Disconnect from the Apple Push Notification Service
         $push->disconnect();
         // Examine the error message container
         $aErrorQueue = $push->getErrors();
         if (!empty($aErrorQueue)) {
             foreach ($aErrorQueue as $error) {
                 // On récupère la liste des token qui ont généré une erreur
                 $var = $error['MESSAGE'];
                 $failedMessages = array_merge($failedMessages, $var->getRecipients());
             }
         }
         return $this->returnResult($failedMessages, $this->registrationTokens);
     } catch (\Exception $e) {
         return $this->returnResult($this->registrationTokens, $this->registrationTokens);
     }
 }
コード例 #9
0
ファイル: content.php プロジェクト: uvaron/GUI
 function ios_push($device_array, $push_title, $message_id)
 {
     // ТаймЗона;
     date_default_timezone_set('Europe/Rome');
     // Подключаем внешнюю библеотеку для работы с Apple свервером;
     require_once $_SERVER['DOCUMENT_ROOT'] . '/systems/api/ApnsPHP/Autoload.php';
     // Создаем объект для сообщения и работы с сервером;
     $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, $_SERVER['DOCUMENT_ROOT'] . '/systems/api/appDistr.pem');
     // Пароль разработчика;
     $push->setProviderCertificatePassphrase('fdu4v9f123');
     // Соединяемся с Яблочным сервером;
     $push->connect();
     foreach ($device_array as $token_temp) {
         // Преобразуем передаваемый IOS токен в человеческий вид;
         // Убираем <> краям;
         $token_temp = substr($token_temp, 1, -1);
         // Убираем пробелы;
         $token_temp_array = explode(' ', $token_temp);
         $token = '';
         for ($i = 0; $i <= count($token_temp_array); $i++) {
             $token = $token . $token_temp_array[$i];
         }
         // Создаем объект сообщения;
         $message = new ApnsPHP_Message($token);
         // Задаем какой-то неведомый параметр;
         $message->setCustomIdentifier("Message-Badge-1");
         // Тип значка?
         $message->setBadge(1);
         // "Я видел некоторое дерьмо" (с);
         $message->setText($push_title);
         // Звук уведомления?
         $message->setSound();
         // Передаем заголовок и ID сообщения;
         $service_message = explode('=', $push_title);
         if ($service_message[0] == 'service') {
             $message->setCustomProperty('service', $service_message[1]);
         } else {
             $message->setCustomProperty('title', $push_title);
             $message->setCustomProperty('message_id', $message_id);
         }
         // сервисное сообщение про обновление бейджей в меню
         //$message->setCustomProperty('service','refresh_badge');
         // Таймаут? Что блин за таймаут?
         $message->setExpiry(30);
         // Добавляем сообщение в сессию;
         $push->add($message);
     }
     // Отправляем сообщение;
     $push->send();
     // Отключаемся от Яблочного сервера;
     $push->disconnect();
 }
コード例 #10
0
 protected function sendPushToDevice($cert, $deviceId, $message, $sn = '')
 {
     if (strlen($deviceId) < 64) {
         return;
     }
     $env = APPLICATION_ENV == 'development' ? ApnsPHP_Abstract::ENVIRONMENT_SANDBOX : ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION;
     $env = ApnsPHP_Abstract::ENVIRONMENT_SANDBOX;
     $push = new ApnsPHP_Push($env, $cert);
     $push->setLogger(new ApnsPHP_Log_Null());
     $push->setConnectTimeout(4000);
     $push->setRootCertificationAuthority(APPLICATION_PATH . '/data/entrust_root_certification_authority.pem');
     $push->connect();
     $apnsMessage = new ApnsPHP_Message($deviceId);
     $apnsMessage->setBadge(1);
     $apnsMessage->setText($message);
     $apnsMessage->setSound();
     $apnsMessage->setCustomProperty('sn', $sn);
     $push->add($apnsMessage);
     $push->send();
     //$push->disconnect();
     $aErrorQueue = $push->getErrors();
     if (!empty($aErrorQueue)) {
         var_dump($aErrorQueue);
     }
 }
 protected function raw_send($tokens, $title, $user_info)
 {
     // No devices, do nothing
     if (empty($tokens)) {
         return 0;
     }
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Abstract.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Exception.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Feedback.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Message.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Log/Interface.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Log/Embedded.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Message/Custom.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Message/Exception.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Push.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Push/Exception.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Push/Server.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Push/Server/Exception.php';
     require_once dirname(__FILE__) . '/../class-pnfw-apnsphp-logger.php';
     $certificate = get_attached_file(get_option("pnfw_production_ssl_certificate_media_id"));
     $passphrase = get_option("pnfw_production_ssl_certificate_password");
     $environment = ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION;
     if (get_option("pnfw_ios_use_sandbox")) {
         $certificate = get_attached_file(get_option("pnfw_sandbox_ssl_certificate_media_id"));
         $passphrase = get_option("pnfw_sandbox_ssl_certificate_password");
         $environment = ApnsPHP_Abstract::ENVIRONMENT_SANDBOX;
     }
     if (empty($certificate)) {
         pnfw_log(PNFW_IOS_LOG, __("iOS SSL certificate is not correctly set.", 'pnfw'));
         return 0;
     }
     if (empty($passphrase)) {
         pnfw_log(PNFW_IOS_LOG, __("iOS SSL certificate password is not correctly set.", 'pnfw'));
         return 0;
     }
     if (!file_exists($certificate)) {
         pnfw_log(PNFW_IOS_LOG, __("iOS SSL Certificate does not exists.", 'pnfw'));
         return 0;
     }
     $pnfw_ios_payload_sound = get_option('pnfw_ios_payload_sound', 'default');
     try {
         $push = new ApnsPHP_Push($environment, $certificate);
         $push->setLogger(new PNFW_ApnsPHP_Logger());
         $push->setProviderCertificatePassphrase($passphrase);
         foreach ($tokens as &$token) {
             try {
                 $this->notification_sent($token);
                 $message = new ApnsPHP_Message($token);
                 foreach (array_keys($user_info) as $key) {
                     $message->setCustomProperty($key, strval($user_info[$key]));
                 }
                 $message->setText($title);
                 $message->setSound($pnfw_ios_payload_sound);
                 $message->setBadge($this->get_badge_count($token));
                 $push->add($message);
             } catch (Exception $e) {
                 // The only exception here is the invalid token, so delete it
                 $this->delete_token($token);
             }
         }
         unset($token);
         $queued = count($push->getQueue(false));
         // Empty queue, do nothing
         if ($queued == 0) {
             return 0;
         }
         // Connect to the Apple Push Notification Service
         $push->connect();
         // Send all messages in the message queue
         $push->send();
         // Disconnect from the Apple Push Notification Service
         $push->disconnect();
         return $queued;
     } catch (Exception $e) {
         pnfw_log(PNFW_IOS_LOG, strip_tags($e->getMessage()));
         return 0;
     }
 }
コード例 #12
0
ファイル: pusher-single.php プロジェクト: Ssmur/appaddict.org
        // over a ApnsPHP_Message object retrieved with the getErrors() message.
        $message->setCustomIdentifier(uniqid());
        // Set badge icon to "3"
        $newbadge = $d['badge'] + 1;
        $badges[$newbadge][] = $d['udid'];
        $message->setBadge($newbadge);
        // Set a simple welcome text
        if ($argv[1]) {
            $message->setText($argv[1]);
        }
        // Play the default sound
        $message->setSound();
        // Set a custom property
        if ($argv[3]) {
            foreach ((array) json_decode($argv[3], true) as $k => $v) {
                $message->setCustomProperty($k, $v);
            }
        }
        $message->setCustomProperty('type', $argv[2]);
        if ($argv[4]) {
            $message->setContentAvailable(true);
        }
        // Set t
        // Set the expiry value to 30 seconds
        $message->setExpiry(86400);
        // Add the message to the message queue
        $push->add($message);
        // Send all messages in the message queue
    }
}
$push->send();
コード例 #13
0
ファイル: APNService.php プロジェクト: gtyd/jira
 /**
  * 发送消息到苹果设备
  * @param array $tokens 设备id
  * @param string $text 消息标题
  * @param array $customProperty 自定义属性
  * @param array $badget 消息在设备显示的红点中的数值
  * @param string $sound 声音
  * @throws \Exception
  * @return array 正常,返回空数组;异常,返回['tokens'=>'err msg']这种格式的错误数组
  */
 public function send($tokens = null, $msg_title = '你收到一个新消息', $msg_property = [], $badget = [], $sound = 'default')
 {
     try {
         $this->push->connect();
         $invaliduser = [];
         $err = [];
         foreach ($tokens as $token) {
             try {
                 $message = new \ApnsPHP_Message($token);
                 $message->setCustomIdentifier($token);
                 //设置消息的小图标(红点中显示的数目
                 $message->setBadge(isset($badget[$token]) ? intval($badget[$token]) : 1);
                 //设置消息显示的标题
                 $message->setText($msg_title);
                 // Play the default sound
                 $message->setSound($sound);
                 // Set a custom property
                 foreach ($msg_property as $key => $value) {
                     $message->setCustomProperty($key, $value);
                 }
                 $message->setExpiry(self::MSG_EXPIRY);
                 // Add the message to the message queue
                 $this->push->add($message);
             } catch (\ApnsPHP_Message_Exception $e) {
                 $invaliduser[] = $token;
                 $err[$token] = $e->getMessage();
             }
         }
         // Send all messages in the message queue
         $this->push->send();
         $this->push->disconnect();
     } catch (\ApnsPHP_Exception $e) {
         return Push::ret(Push::ERR_IOS_SEND_FAIL, $e->getMessage());
     }
     $aErrorQueue = $this->push->getErrors();
     if (!empty($aErrorQueue)) {
         foreach ($aErrorQueue as $err) {
             $invaliduser[] = $err['MESSAGE']->getCustomIdentifier();
             $err[$err['MESSAGE']->getCustomIdentifier()] = json_encode($err['ERRORS']);
         }
     }
     if (empty($err)) {
         return Push::ret(Push::ERR_OK, 'ok', []);
     } else {
         return Push::ret(Push::ERR_OK, json_encode($err), $invaliduser);
     }
 }
コード例 #14
0
ファイル: APNS.php プロジェクト: CFLOVEYR/hook
 /**
  * push
  * @param mixed $registrations
  * @param mixed $data
  */
 public function push($registrations, $data)
 {
     $apns_environment = Config::get('push.apns.environment', 'sandbox');
     $apns_certificate_file = Config::get('push.apns.cert.file', false);
     $apns_certificate_pass = Config::get('push.apns.cert.pass', false);
     if (!$apns_certificate_file) {
         throw new \Exception("APNS config error: 'push.apns.cert.file' not set.");
     }
     $total_failure = 0;
     // Instantiate a new ApnsPHP_Push object
     $push = new \ApnsPHP_Push($apns_environment == 'sandbox' ? \ApnsPHP_Abstract::ENVIRONMENT_SANDBOX : \ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, $this->getCertificateFile($apns_certificate_file));
     // set custom logger
     $push->setLogger(new APNSLogger());
     // Set the Provider Certificate passphrase
     if ($apns_certificate_pass) {
         $push->setProviderCertificatePassphrase($apns_certificate_pass);
     }
     // Set the Root Certificate Autority to verify the Apple remote peer
     $push->setRootCertificationAuthority($this->getRootCertificationAuthority());
     // Connect to the Apple Push Notification Service
     $push->connect();
     $message = new \ApnsPHP_Message();
     // Add all registrations as message recipient
     foreach ($registrations as $registration) {
         try {
             $message->addRecipient($registration->device_id);
         } catch (\ApnsPHP_Message_Exception $e) {
             Logger::error($e->getMessage());
             $total_failure += 1;
         }
     }
     Logger::debug("Recipients => " . json_encode($message->getRecipients()));
     // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
     // over a ApnsPHP_Message object retrieved with the getErrors() message.
     if (isset($data['custom_identifier'])) {
         $message->setCustomIdentifier($data['custom_identifier']);
     }
     // Set badge icon to "3"
     if (isset($data['badge']) && is_int($data['badge'])) {
         $message->setBadge((int) $data['badge']);
     }
     // Set text
     $message->setText($data['message']);
     // Play the default sound
     if (!isset($data['sound']) || empty($data['sound'])) {
         $data['sound'] = 'default';
     }
     $message->setSound($data['sound']);
     // Set the expiry value to 30 seconds
     if (isset($data['expiry']) && $data['expiry'] > 0) {
         $message->setExpiry($data['expiry']);
     }
     // Set custom properties
     $invalid_properties = array('_id', 'app_id', 'created_at', 'updated_at', 'sound', 'text', 'badge', 'expiry', 'custom_identifier');
     $custom_properties = array_diff_key($data, array_flip($invalid_properties));
     foreach ($custom_properties as $property => $value) {
         $message->setCustomProperty($property, $value);
     }
     // Add the message to the message queue
     $push->add($message);
     // Send all messages in the message queue
     $stats = $push->send();
     // Disconnect from the Apple Push Notification Service
     $push->disconnect();
     // Examine the error message container
     $error_list = $push->getErrors();
     // Log delivery status
     $errors = $push->getErrors();
     $total_failure += count($errors);
     if ($total_failure > 0) {
         foreach ($errors as $error) {
             Logger::error($error);
         }
     }
     return array('success' => $registrations->count() - $total_failure, 'failure' => $total_failure);
 }
コード例 #15
0
ファイル: IOS.php プロジェクト: irontec/push-notifications
 /**
  * Gestiona el envio de las notificaciones con la libreria "ApnsPHP"
  */
 public function send()
 {
     if ($this->getEnvironment() === 1) {
         $push = new \ApnsPHP_Push($this->getEnvironment(), $this->getPemDev());
         $push->setProviderCertificatePassphrase($this->getPassphraseDev());
     } else {
         $push = new \ApnsPHP_Push($this->getEnvironment(), $this->getPem());
         $push->setProviderCertificatePassphrase($this->getPassphrase());
     }
     $push->setWriteInterval($this->getWriteInterval());
     $push->setSendRetryTimes($this->getSendRetryTimes());
     $push->setConnectTimeout($this->getConnectTimeout());
     $push->connect();
     try {
         $message = new \ApnsPHP_Message($this->getDeviceToken());
         $message->setText($this->getMessage());
         $message->setSound();
         if (!empty($this->getExtraData())) {
             foreach ($this->getExtraData() as $key => $value) {
                 $message->setCustomProperty($key, $value);
             }
         }
         $message->setExpiry($this->getExpiry());
         $push->add($message);
         $push->send();
         $push->disconnect();
         $aErrorQueue = $push->getErrors();
     } catch (\Exception $e) {
         $aErrorQueue = array($e->getMessage());
     }
     if (!empty($aErrorQueue)) {
         return $aErrorQueue;
     }
     return true;
 }