Cam*_*nor 9 php apple-push-notifications ios swift
Apple已更新其推送通知服务,收到的证书文件现在是.p8文件.网上有很多关于如何使用.pem文件发送推送通知的例子,但我找不到.p8文件的任何内容.有没有人有任何与.p8文件一起使用的代码?
使用下面的脚本,我可以使用.p8文件发送基于令牌的推送通知。
支持此功能的最低版本的curl是7.38.0,并且必须使用--with-nghttp2标志和openssl> = 1.0.2进行编译。
<?php
$keyfile = 'AuthKey_AABBCC1234.p8'; # <- Your AuthKey file
$keyid = 'AABBCC1234'; # <- Your Key ID
$teamid = 'AB12CD34EF'; # <- Your Team ID (see Developer Portal)
$bundleid = 'com.company.YourApp'; # <- Your Bundle ID
$url = 'https://api.development.push.apple.com'; # <- development url, or use http://api.push.apple.com for production environment
$token = 'e2c48ed32ef9b018........'; # <- Device Token
$message = '{"aps":{"alert":"Hi there!","sound":"default"}}';
$key = openssl_pkey_get_private('file://'.$keyfile);
$header = ['alg'=>'ES256','kid'=>$keyid];
$claims = ['iss'=>$teamid,'iat'=>time()];
$header_encoded = base64($header);
$claims_encoded = base64($claims);
$signature = '';
openssl_sign($header_encoded . '.' . $claims_encoded, $signature, $key, 'sha256');
$jwt = $header_encoded . '.' . $claims_encoded . '.' . base64_encode($signature);
// only needed for PHP prior to 5.5.24
if (!defined('CURL_HTTP_VERSION_2_0')) {
define('CURL_HTTP_VERSION_2_0', 3);
}
$http2ch = curl_init();
curl_setopt_array($http2ch, array(
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
CURLOPT_URL => "$url/3/device/$token",
CURLOPT_PORT => 443,
CURLOPT_HTTPHEADER => array(
"apns-topic: {$bundleid}",
"authorization: bearer $jwt"
),
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $message,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADER => 1
));
$result = curl_exec($http2ch);
if ($result === FALSE) {
throw new Exception("Curl failed: ".curl_error($http2ch));
}
$status = curl_getinfo($http2ch, CURLINFO_HTTP_CODE);
echo $status;
function base64($data) {
return rtrim(strtr(base64_encode(json_encode($data)), '+/', '-_'), '=');
}
?>
Run Code Online (Sandbox Code Playgroud)
小智 1
我一直在尝试使用 PHP 使用基于 JWT 的新推送通知服务发送推送通知。这绝对不是一件容易的事。
我已将项目上传到GitHub上。您可以从那里下载并确保将 .p8 文件替换为现有的 .p8 文件。
然后在push.php
文件中您需要替换您的kid
, iss(Team ID)
,token
和app_bundle_id
.
转到目录并从终端运行命令php push.php
。如果一切顺利,那么您应该会收到推送通知。
这个解决方案对我来说效果很好。只需确保终端中没有出现任何错误即可。
我希望这有帮助。