/** * Send the given notification with Apple Push Notification Service Server. * * @param Notification $notification the notification to send * @return boolean true on success, false if there was an error. */ public function send($notification) { $config = Config::getInstance(); $appRoot = $config->getString('appRootDir'); // Instanciate a new ApnsPHP_Push object, with the provider certificate $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, $appRoot . $config->getString('monitoring/notification/push/providerCertificateDir')); // Set custom logger $push->setLogger(new ApnsPHP_Log_Fruition()); // Set the Provider Certificate passphrase $push->setProviderCertificatePassphrase($config->getString('monitoring/notification/push/passphrase')); // Set the Root Certificate Autority to verify the Apple remote peer $push->setRootCertificationAuthority($appRoot . $config->getString('monitoring/notification/push/rootCertificateAuthorityDir')); // Get recipient list. If no registration id (user did not connect to the // mobile app, we stop the process $stringRecipients = $notification->getRecipient(); if (empty($stringRecipients)) { Logger::info("No registration id was found. The notification is not sent."); return false; } // Connect to the Apple Push Notification Service $push->connect(); // Create a message for each device $message = new ApnsPHP_Message(); $message->setText($notification->getContent()); $message->setSound(); $message->setExpiry(30); // 60 seconds $recipientList = explode(",", $notification->getRecipient()); foreach ($recipientList as $registrationId) { $message->addRecipient($registrationId); } // 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)) { foreach ($aErrorQueue as $error) { foreach ($error['ERRORS'] as $err) { //For statusCode = 8, which is Invalid Token, we delete the token. if ($err['statusCode'] == self::INVALID_TOKEN) { if ($this->handlerErrorCallBack) { $token = $error['MESSAGE']->getRecipient(); call_user_func($this->handlerErrorCallBack, $token); } } Logger::error("Sending push notification failed. Error code: " . $err['statusCode'] . ". Message: " . $err['statusMessage']); } } return false; } //If success Logger::info("Notification sent with device token " . $notification->getRecipient()); return true; }
private static function sendToIOS($token, $message) { /*$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, 'com.appkode.yol');*/ $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, ROOT . '/app/config/apns-dev.pem'); $disabledLogger = new DisabledLogger(); $push->setProviderCertificatePassphrase('test123'); $push->setLogger($disabledLogger); // $push->setRootCertificationAuthority(ROOT . '/app/config/apns-dev.pem'); $push->connect(); $apnsMessage = new ApnsPHP_Message(); $apnsMessage->setText($message); $apnsMessage->addRecipient($token); $push->add($apnsMessage); $push->send(); $push->disconnect(); $error = $push->getErrors(); if (is_array($error) && count($error) > 0) { self::log('iOS error: ' . "\n" . json_encode($error)); } else { self::log('Push is sent'); } }
/** * @param array|string $tokens * @param $text * @param array $payloadData * @param array $args * @return \ApnsPHP_Message|null */ public function sendMulti($tokens, $text, $payloadData = [], $args = []) { $tokens = is_array($tokens) ? $tokens : [$tokens]; // check if its dry run or not if ($this->dryRun === true) { $this->log($tokens, $text, $payloadData, $args = []); return null; } $message = new \ApnsPHP_Message(); foreach ($tokens as $token) { $message->addRecipient($token); } //$message->setText($text); foreach ($args as $method => $value) { if (strpos($message, 'set') === false) { $method = 'set' . ucfirst($method); } $value = is_array($value) ? $value : [$value]; call_user_func_array([$message, $method], $value); } $message->setText($text); // 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; }
function SendIOS($tokens, $text, $config) { # Создаём экземпляр Push. Необходимо указывать параметр ENVIRONMENT_PRODUCTION или # ENVIRONMENT_SANDBOX в соответствии с сертификатом. $push = new ApnsPHP_Push($config['apn']['production'] ? 0 : 1, $config['apn']['production'] ? $config['apn']['sert_prod'] : $config['apn']['sert']); # Указываем пароль сертификата если он имеется if ($config['apn']['sertPass'] != '') { $push->setProviderCertificatePassphrase($config['apn']['sertPass']); } # Указываем корневой сертификат $push->setRootCertificationAuthority($config['apn']['RootCertificat']); # Создаём сообщение $message = new ApnsPHP_Message(); # Перебираем массив токенов и добавляем получателей $listTokens = array(); foreach ($tokens as $token) { $message->addRecipient($token); $listTokens[] = $token; } # Соединяемся с сервером $push->connect(); # Устанавливаем параметры отправки сообщения $message->setSound(); //$message->setBadge(0) $message->setText($text); # Устанавливаем сообщение для отправки $push->add($message); # Отправляем сообщение $push->send(); # Отключаемся от сервера $push->disconnect(); # Проверяем возникшие ошибки во время отправки $aErrorQueue = $push->getErrors(); # Если имеются ошибки if (!empty($aErrorQueue)) { echo 'Ошибка отправки ios - ' . print_r($aErrorQueue, true); if (is_array($aErrorQueue)) { foreach ($aErrorQueue as $error) { if (isset($error['ERRORS']) && is_array($error['ERRORS'])) { foreach ($error['ERRORS'] as $m) { if (isset($m['statusMessage']) && $m['statusMessage'] == 'Invalid token') { $arrayID = $m['identifier'] - 1; if (isset($listTokens[$arrayID])) { # Если найден недействительный токен, удатяем его из БД //echo 'Удаление ошибочного токена'; DeleteToken($listTokens[$arrayID]); } } } } } } } }
/** * 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); }