簡體   English   中英

使用 .p8 文件在 php 中發送 iOS 推送通知

[英]Send iOS Push notification in php with .p8 file

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)), '+/', '-_'), '=');
  }

?>

我也很難找到一個簡單的庫來使用 PHP 中的 .p8 文件發送 APNS 通知。 我發現edamov/pushok庫是最直接和面向對象的。 只需使用composer require edamov/pushok安裝軟件包並按照入門中的說明進行操作。

我一直在嘗試使用 PHP 使用基於 JWT 的推送通知服務發送推送通知。 這絕對不是一件容易的事。

我已經在GitHub 上上傳了項目。 您可以從那里下載並確保將 .p8 文件替換為現有的 .p8 文件。

然后在push.php文件,你需要更換你的kidiss(Team ID) tokenapp_bundle_id

轉到目錄並從終端運行命令php push.php 如果一切順利,您應該會收到推送通知。

這個解決方案對我很有效。 只要確保您在終端中沒有收到任何錯誤。

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM