我正在编写使用PHP Laravel向Apple推送通知服务器(apn)发送通知的代码。它在文档中说它需要HTTP/HPACK头压缩。
我试过使用cURL
$cURLConnection = curl_init();
if(strcmp(env('APP_ENV'), 'production') == 0) {
curl_setopt($cURLConnection, CURLOPT_URL, 'api.push.apple.com:443');
} else {
curl_setopt($cURLConnection, CURLOPT_URL, 'api.development.push.apple.com:443');
}
curl_setopt_array($cURLConnection, [
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_HTTP_VERSION =>CURL_HTTP_VERSION_2_0,
]);
curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, array(
'path: /3/device/<devicetoken>',
'authorization: bearer ' . $token,
'Content-Type: application/json'
));
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $postRequest);
curl_setopt ($cURLConnection, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
$apiResponse = curl_exec($cURLConnection);
但是APNS服务器总是返回'Empty reply from server'
我看到一些可能有问题的地方。
尝试添加以下内容以实际将您的请求转换为POST请求。
curl_setopt($c, CURLOPT_POST, 1);
你的"路径"也应该是主URL的一部分,而不是作为标题添加。
curl_setopt($c, CURLOPT_URL, "https://api.push.apple.com:443/3/device/<devicetoken>");
除了前面的建议,我们还应该能够使用证书基auth system.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://path-to-auth-example.com/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_cert");
curl_setopt($ch, CURLOPT_SSLCERT, "path/to/your/pem-file.pem");
curl_setopt($ch, CURLOPT_SSLCERTTYPE, "PEM");
$headers = [];
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
//catch your error wisely
}
curl_close($ch);
$result = json_decode($result);
print_r($result);
?>