Initially we were sending the APNs notification by using PEM file. But now as suggested by Apple and migrated and sending the iOS Push notification via p8 file like Establishing a Token-Based Connection to APNs.
Currently we are sending the iOS Push notification by using PHP file. In production, we are facing bad device toekn issue while sending the notification. I dont know why we are getting this issue. problem is if device token length more than 50, then no issue and deliver it successfully. if device token length less than 50, bad device token received and httpcode : 400.
Suggest, how will proceed further.
Sample Code
<?php
// only needed for PHP prior to 5.5.24
if (!defined('CURL_HTTP_VERSION_2_0')) {
define('CURL_HTTP_VERSION_2_0', 3);
}
// THE FINAL SCRIPT WITHOUT DEPENDENCIES!!! except curl with http2
$device_token = "<less than 50 length>";
//echo $key;
$kid = "<our key>";
$teamId = "<our team id>";
$app_bundle_id = "<our package bundle id>";
$base_url = "https://api.push.apple.com";
$header = array("alg" => "<Sample>", "kid" => $kid);
$header = base64_encode(json_encode($header));
$claim = array("iss" => $teamId, "iat" => time());
$claim = base64_encode(json_encode($claim));
$token = $header.".".$claim;
// key in same folder as the script
$filename = "<FILE>.p8";
$pkey = openssl_pkey_get_private("file://{$filename}");
$signature;
openssl_sign($token, $signature, $pkey, 'sha256');
$sign = base64_encode($signature);
$jws = $token.".".$sign;
$message = '<Sample>';
function sendHTTP2Push($curl, $base_url, $app_bundle_id, $message, $device_token, $jws) {
$url = "{$base_url}/3/device/{$device_token}";
// headers
$headers = array(
"apns-topic: {$app_bundle_id}",
'Authorization: bearer ' . $jws
);
// other curl options
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
CURLOPT_URL => $url,
CURLOPT_PORT => 443,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $message,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HEADER => 1,
CURLOPT_SSL_VERIFYPEER => false
));
// go...
$result = curl_exec($curl);
print_r($result);
die;
if ($result === FALSE) {
throw new Exception("Curl failed: " . curl_error($curl));
}
print_r($result."\n");
// get response
$status = curl_getinfo($curl);
return $status;
}
// open connection
$curl = curl_init();
sendHTTP2Push($curl, $base_url, $app_bundle_id, $message, $device_token, $jws);
?>