function send_message($key, $text, $badge = 0) { $socket = new ApnsPHP_Push($this->environment, $this->certificate_path); $socket->setRootCertificationAuthority($this->root_certificate_path); $socket->connect(); $message = new ApnsPHP_Message($key); $message->setCustomIdentifier('notification'); $message->setBadge($badge); $message->setText($text); $message->setSound(); $message->setExpiry(30); $socket->add($message); try { $socket->send(); $socket->disconnect(); } catch (Exception $e) { return false; } $errors = $socket->getErrors(); if (!empty($errors)) { return false; } return true; }
/** * 送信処理 */ public function push($tokens, $text, $pem, $options = array()) { // pemファイルの有無 if (!file_exists(ROOT . DS . APP_DIR . DS . $this->app_cert_path . $pem)) { $this->log(__LINE__ . '::' . __METHOD__ . '::' . ' non pem file. => ' . $pem, LOG_ERR); return false; } $push = new ApnsPHP_Push($this->env, ROOT . DS . APP_DIR . DS . $this->app_cert_path . $pem); $push->setRootCertificationAuthority(ROOT . DS . APP_DIR . DS . $this->entrust_cert_path); $push->connect(); // 失敗したトークンの一時保存用 $invalid_tokens = array(); try { foreach ((array) $tokens as $key => $token) { try { $message = new ApnsPHP_Message($token['Device']['token']); $message->setText($text); $message->setSound(); $message->setCustomIdentifier(isset($options['identifier']) ? $options['identifier'] : $this->identifier); $message->setExpiry(isset($options['identifier']) ? $options['expiry'] : $this->expiry); $push->add($message); $this->log(__LINE__ . '::' . __METHOD__ . '::' . ' Send Token [' . $token['Device']['token'] . ']', LOG_DEBUG); } catch (Exception $e) { $this->log(__LINE__ . '::' . __METHOD__ . '::' . ' iOS Notification Error [' . $token['Device']['token'] . ']', LOG_ERR); array_push($invalid_tokens, $token['Device']['token']); } $push->send(); } } catch (Exception $e) { $this->log(__LINE__ . '::' . __METHOD__ . '::' . ' iOS Notification Error: ' . $e->getMessage(), LOG_ERR); array_push($invalid_tokens, $token['Device']['token']); } // 送信失敗していたら対象のトークンを一旦保持 $aErrorQueue = $push->getErrors(); $push->disconnect(); if (!empty($aErrorQueue)) { foreach ($aErrorQueue as $info) { if (isset($info['ERRORS'])) { foreach ($info['ERRORS'] as $error) { if (isset($error['statusMessage']) && $error['statusMessage'] == 'Invalid token') { $this->log(__LINE__ . '::' . __METHOD__ . '::' . $error['statusMessage'] . ' [' . $token['Device']['token'] . ']', LOG_ERR); array_push($invalid_tokens, $token['Device']['token']); } } } } } // 失敗したトークンへは配信しないようにフラグを変更 if (!empty($invalid_tokens)) { $this->allow_disible($invalid_tokens); } if (empty($aErrorQueue)) { return true; } else { $this->log(__LINE__ . '::' . __METHOD__ . '::' . ' iOS Notification Error: ' . $aErrorQueue, LOG_ERR); return false; } }
/** * 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; }
/** * @see AM_Task_Worker_Abstract::_fire() * @throws AM_Task_Worker_Exception * @return void */ protected function _fire() { $aTokens = (array) $this->getOption('tokens'); $sMessage = $this->getOption('message'); $iBadge = intval($this->getOption('badge')); // Instanciate a new ApnsPHP_Push object $oPushService = $this->getPushService(); // Connect to the Apple Push Notification Service $oPushService->connect(); foreach ($aTokens as $sToken) { // Instantiate a new Message with a single recipient $oPushMessage = new ApnsPHP_Message($sToken); $oPushMessage->setText($sMessage); $oPushMessage->setBadge($iBadge); // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method // over a ApnsPHP_Message object retrieved with the getErrors() message. $oPushMessage->setCustomIdentifier(sprintf('%s', $sToken)); // Add the message to the message queue $oPushService->add($oPushMessage); } // Send all messages in the message queue $oPushService->send(); // Disconnect from the Apple Push Notification Service $oPushService->disconnect(); // Examine the error message container $aErrorQueue = $oPushService->getErrors(); if (!empty($aErrorQueue)) { $aErrors = array(); foreach ($aErrorQueue as $aError) { /* @var $oMessage ApnsPHP_Message */ $oMessage = $aError['MESSAGE']; //Get last error message $aMessageError = array_pop($aError['ERRORS']); $aErrors[$oMessage->getCustomIdentifier()] = $aMessageError; } $this->addOption('errors', $aErrors); throw new AM_Task_Worker_Exception('Messages have an unrecoverable errors'); } }
// Report all PHP errors error_reporting(-1); // Using Autoload all classes are loaded on-demand require_once 'ApnsPHP/Autoload.php'; // Instanciate a new ApnsPHP_Push object $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'server_cerificates_bundle_sandbox.pem'); // Set the Root Certificate Autority to verify the Apple remote peer $push->setRootCertificationAuthority('entrust_root_certification_authority.pem'); // 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
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(); }
// Instanciate a new ApnsPHP_Push object $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'server_certificates_bundle_sandbox.pem'); // Set the Root Certificate Autority to verify the Apple remote peer $push->setRootCertificationAuthority('entrust_root_certification_authority.pem'); // Increase write interval to 100ms (default value is 10ms). // This is an example value, the 10ms default value is OK in most cases. // To speed up the sending operations, use Zero as parameter but // some messages may be lost. // $push->setWriteInterval(100 * 1000); // Connect to the Apple Push Notification Service $push->connect(); for ($i = 1; $i <= 10; $i++) { // Instantiate a new Message with a single recipient $message = new ApnsPHP_Message($i == 5 ? INVALID_TOKEN : VALID_TOKEN); // 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(sprintf("Message-Badge-%03d", $i)); // Set badge icon to "3" $message->setBadge($i); // 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); }
// Set the Provider Certificate passphrase // $push->setProviderCertificatePassphrase('test'); // Set the Root Certificate Autority to verify the Apple remote peer //$push->setRootCertificationAuthority('push_certs/entrust_root_sandbox.cer'); // Connect to the Apple Push Notification Service $push->connect(); $notification_type = $argv[5]; $devices = $API->DB->query_return("SELECT push.*, accounts.push_notifications FROM push LEFT JOIN accounts ON push.account_id=accounts.id WHERE udid IN(" . implode(',', array_map(array($API->DB, 'sqlesc'), explode(',', $argv[6]))) . ")"); foreach ($devices as $d) { $push_notificaions = explode(',', $d['push_notifications']); if ($push_notificaions[0] != 'none' || !$push_notificaions[0] || in_array($notification_type, $push_notificaions)) { // Instantiate a new Message with a single recipient $message = new ApnsPHP_Message($d['token']); // 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(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); }
/** * 发送消息到苹果设备 * @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); } }
/** * 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); }