iOS 建立遠距推播 App (五) 推播測試 – 使用 php
1.伺服器檢查事項
(1) Web Server 需支援 HTTP/2
檢測方法一 : For Linux
$ curl --http2 -I https://www.google.com
不支援出現 :
curl : (1) Unsupported protocol
檢測方式二 : 使用 php
<?php
echo $_SERVER[ "SERVER_PROTOCOL" ];
(2) PHP 版本需 5.5.24 版以上 php 的 curl 才有支援 HTTP/2
2. PHP 程式碼
<?php
$team_id=""; //開發者 team ID
$key_id=""; //p8 格式證書的 ID
$pkey_file="AuthKey_xxxxxx.p8"; //p8證書的存放位址,勿使用中文。絕對路徑
$bundle_id=""; //App的 Boundle ID
$device_token=""; //Device token
$msg="測試訊息";
$r=Sent_Notification_iOS($team_id ,$key_id,$pkey_file,$bundle_id,$device_token,$msg);
function Sent_Notification_iOS($team_id ,$key_id,$pkey_file,$bundle_id,$device_token,$msg){
// Create the notification payload
$payload = array(
'aps' => array(
'alert' => $msg,
'sound' => 'default'
)
);
$payload_json = json_encode($payload);
//正式環境推送
//$url = 'https://api.push.apple.com/3/device/' . $device_token;
//沙盒推送地址
$url = "https://api.sandbox.push.apple.com/3/device/".$device_token;
$jwt = get_JWT($team_id ,$key_id,$pkey_file,$bundle_id);
$headers = array(
'Authorization: Bearer '.$jwt,
'Content-Type: application/json',
'apns-topic: '.$bundle_id,
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload_json);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); //這里很關鍵,以http2發送請求,如果你的curl不支持http2則需要看前面的步驟
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
var_dump($response);
curl_close($ch);
// Check the response
if ($http_code == 200) {
echo 'Notification sent successfully.';
} else {
echo 'Notification failed with error code: ' . $http_code;
}
}
function get_JWT($team_id ,$key_id,$pkey_file,$bundle_id){
// token過期時間
$expires = time() + 3600;
// Generate the JWT header
$header = array(
'alg' => 'ES256',
'kid' => $key_id
);
$jwt_header = base64_encode(json_encode($header));
// Generate the JWT payload
$payload = array(
'iss' => $team_id,
'iat' => time()
);
$jwt_payload = base64_encode(json_encode($payload));
//載入證書文件
$pkey_contents = file_get_contents($pkey_file);
$pkey = openssl_get_privatekey($pkey_contents);
//JWT 簽名
$signature = '';
openssl_sign($jwt_header . '.' . $jwt_payload, $signature, $pkey, 'sha256');
$jwt_signature = base64_encode($signature);
// Generate the final JWT
$jwt = $jwt_header . '.' . $jwt_payload . '.' . $jwt_signature;
return $jwt;
}