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

问题描述 投票:8回答:3

Apple已更新了其推送通知服务,现在收到的证书文件是.p8文件。在线上有很多示例,它们说明如何使用.pem文件发送推送通知,但是我找不到.p8文件的任何内容。任何人都没有任何适用于.p8文件的代码吗?

php ios swift apple-push-notifications
3个回答
8
投票

使用下面的脚本,我可以使用.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)), '+/', '-_'), '=');
  }

?>

0
投票

我一直在尝试使用PHP使用新的JWT based push notification service发送推送通知。这绝对不是一件容易的事。

我已经在GitHub上上传了项目。您可以从那里下载并确保将.p8文件替换为现有的.p8文件。

然后在push.php文件中,您需要替换kidiss(Team ID)tokenapp_bundle_id

转到目录,然后从终端运行命令php push.php。如果一切顺利,那么您应该会收到推送通知。

此解决方案对我来说效果很好。只要确保您在终端上没有任何错误即可。

我希望这会有所帮助。


0
投票

我还很难找到一个简单的库来用PHP发送带有.p8文件的APNS通知。我发现edamov/pushok库是最直接,最面向对象的。只需使用composer require edamov/pushok安装该软件包,然后按照Getting Started中的说明进行操作。

© www.soinside.com 2019 - 2024. All rights reserved.