Как подключиться к apn с помощью PHP с помощью файла ключа аутентификации p8

После того, как Apple изменила ключ аутентификации APN на p8, текущие библиотеки, такие как https://github.com/immobiliare/ApnsPHP по-прежнему использовать старые файлы pem и cert для подключения

$push = new ApnsPHP_Push(
ApnsPHP_Abstract::ENVIRONMENT_SANDBOX,
'server_certificates_bundle_sandbox.pem'
);
// Set the Provider Certificate passphrase
// $push->setProviderCertificatePassphrase('test');
// 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()

С примером Node.js (https://eladnava.com/send-push-notifications-to-ios-devices-using-xcode-8-and-swift-3/), Я мог бы отправить так:

var apnProvider = new apn.Provider({
token: {
key: 'APNsAuthKey_Q34DLF6Z6J.p8', // Path to the key p8 file
keyId: 'Q34DLF6Z6J', // The Key ID of the p8 file (available at https://developer.apple.com/account/ios/certificate/key)
teamId: 'RLAHF6FL89', // The Team ID of your Apple Developer Account (available at https://developer.apple.com/account/#/membership/)
},
production: false // Set to true if sending a notification to a production iOS app
});

Как я могу использовать PHP для отправки удаленных уведомлений на iOS, как я это делаю в node.js?

9

Решение

Может быть, уже слишком поздно, но у меня была проблема с этим, потому что почти каждая инструкция по старому.

Поэтому я решил ответить на этот «старый» вопрос своим решением.

private static function sendNotificationAPN($device_token, $title, $body, $category, $sound, $optionals) {
$alert = array(
'aps' => array(
'alert'    => array(
'title' => $title,
'body'  => $body
),
'badge' => 0,
'sound'    => $sound,
'category' => $category,
'content-available' => true
)
);

foreach ($optionals as $key => $option) {
$alert[$key] = $option;
}

$alert = json_encode($alert);

$url = 'https://api.development.push.apple.com/3/device/' . $device_token['apn'];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $alert);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("apns-topic: '/* your app name */'"));
curl_setopt($ch, CURLOPT_SSLCERT, /* absolute path to cert file */);
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, /* passphrase for cert */);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);$ret = array(
'body' => $response,
'httpcode' => $httpcode
);

return $ret;
}
2

Другие решения

Извините за опоздание на игру. Если я правильно понимаю ваш вопрос, я считаю, что это то, что вы ищете. Это то, что я использую для отправки сообщений в Apple APNS с использованием PHP. Возможно, вам придется провести некоторое исследование полезной нагрузки, поскольку есть несколько способов структурировать ее в зависимости от того, как вы кодировали свое приложение. Кроме того, имейте в виду, что вы должны иметь возможность использовать порт 2195, чтобы это работало. Если вы используете выделенный или внутренний сервер, все будет в порядке. Если это общий сервер, он не будет работать.

    $passphrase = 'xxxxx'; // This is the passphrase used for file ck.pem
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem'); // ck.pem file must be included to sent token to ios devices
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
stream_context_set_option($ctx, 'ssl', 'verify_peer', true);
stream_context_set_option($ctx, 'ssl', 'allow_self_signed', true);
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
stream_set_blocking ($fp, 0); // Ensure that blocking is disabled

if (!$fp) {
$fds = "Failed to connect: $err $errstr" . PHP_EOL;
return false;
} else {

// Create the payload body
// this example uses a custom data payload.  depending on your app you may need to change this
$body['aps'] = array('alert' => $message, 'sound' => 'default', 'badge' => 1);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', str_replace(' ', '',$token)) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
// Close the connection to the server
fclose($fp);
}
-1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector