Служба push-уведомлений Apple подключается, но уведомление не полученоPhp

Кемеровские программисты php общаются здесь
Anonymous
Служба push-уведомлений Apple подключается, но уведомление не получено

Сообщение Anonymous »

Всю последнюю неделю я бился головой о стену, пытаясь получить эту работу. Я только что начал с нуля и записал все, что делал, но все равно не работает. Вот шаги, которые я предпринял:

1) Создайте новый идентификатор приложения, используя новый идентификатор пакета (в старом не было push-уведомлений)

Код: Выделить всё

a) made sure push notifications were added to the app id and proceeded to the last step, this resulted in an app id with push notifications in the ‘configurable’ state.

b) I then went to edit the app id and saw that i could create a new production or development certificate so i did both using the steps listed
2) Созданы два новых профиля обеспечения: один для разработки и один для производства, оба используют новый идентификатор пакета.

3) импортируйте новые профили обеспечения в Xcode и убедитесь, что именно они выбраны в настройках сборки

4) создайте файлы .p12 с помощью связка ключей и экспорт файлов .cer для разработки и производства

5) создайте файл .pem из файлов .p12 с помощью следующих команд:

Код: Выделить всё

openssl pkcs12 -in VX-Mobile-Dev.p12 -out apns-dev.pem -nodes -clcerts

openssl pkcs12 -in VX-Mobile-Prod.p12 -out apns-prod.pem -nodes -clcerts
6) Затем создал PHP-скрипт (который я явно скопировал из другого блога), который запускаю из командной строки одной из моих виртуальных машин. В ту же папку, что и этот файл, я поместил файл pans-prod.pem. Вот содержимое этого файла

Обратите внимание: для токена устройства я просто запускаю приложение из Xcode, где оно уже успешно подключается к серверу apns и получает токен устройства, который выходит из консоли, в целях тестирования я просто каждый раз копирую новый токен в файл.

Содержимое файла:

Код: Выделить всё

// set time limit to zero in order to avoid timeout
set_time_limit(0);

// charset header for output
header('content-type: text/html; charset: utf-8');

// this is the pass phrase you defined when creating the key
$passphrase = '{passphrase is hidden to you!}';

// you can post a variable to this string or edit the message here
if (!isset($_POST['msg'])) {
$_POST['msg'] = "Notification message here!";
}

// function for fixing Turkish characters
function tr_to_utf($text) {
$text = trim($text);
$search = array('Ü', 'Þ', 'Ð', 'Ç', 'Ý', 'Ö', 'ü', 'þ', 'ð', 'ç', 'ý', 'ö');
$replace = array('Ü', 'Åž', 'Ğž', 'Ç', 'İ', 'Ö', 'ü', 'ÅŸ', 'ÄŸ', 'ç', 'ı', 'ö');
$new_text = str_replace($search, $replace, $text);
return $new_text;
}

// tr_to_utf function needed to fix the Turkish characters
$message = tr_to_utf($_POST['msg']);

// load your device ids to an array
$deviceIds = array(
'97c8c0a77e1380d052d17352e33b1f2224f082a3436ee90310cf88c7278329e7'
);

// this is where you can customize your notification
$payload = '{"aps":{"alert":"' . $message . '","sound":"default"}}';

$result = 'Start' . "\r\n";

////////////////////////////////////////////////////////////////////////////////
// start to create connection
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'apns-prod.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

echo count($deviceIds) . " devices will receive notifications.\r\n";

foreach ($deviceIds as $item) {
// wait for some time
sleep(1);

// Open a connection to the APNS server
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);

if (!$fp) {
exit("Failed to connect: $err $errstr" . "\r\n");
} else {
echo 'Apple service is online. ' . "\r\n";
}

// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload;

// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));

if (!$result) {
echo 'Undelivered message count: ' . $item . "\r\n";
} else {
echo("\r\nRESULT\r\n\r\n");
var_dump($result);
echo("\r\n\r\n");
echo 'Delivered message count: ' . $item . "\r\n";
}

if ($fp) {
fclose($fp);
echo 'The connection has been closed by the client' . "\r\n";
}
}

echo count($deviceIds) . " devices have received notifications.\r\n";

// set time limit back to a normal value
set_time_limit(30);
Пожалуйста, помогите.

Подробнее здесь: https://stackoverflow.com/questions/370 ... s-recieved

Вернуться в «Php»