php - 是否可以使用服务器(使用 PHP)发送 IOS 推送通知?
问题描述
我正在尝试使用 Web 服务器和 PHP 发送推送通知。我曾尝试使用类似问题(https://stackoverflow.com/a/45676540/11051450)的答案中的代码,但由于某种原因我无法使其工作。我认为这可能是因为此代码不是针对 Web 服务器的。在链接的答案中,他们还强调您需要 curl 版本 7.38.0,但我认为我的 Web 服务器只有 curl 版本 7.29.0。这是我尝试使用的代码:
<?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($keyfile);
$header = ['alg'=>'ES256','kid'=>$keyid];
$claims = ['iss'=>$teamid,'iat'=>time()];
$header_encoded = base64($header);
$claims_encoded = base64($claims);
$signature = ''; //should I put a password here?
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)), '+/', '-_'), '=');
}
?>
所以我的问题是,正如标题所解释的那样,您是否能够使用网络服务器向 IOS 设备发送推送通知,以及是否可以提示我应该如何做/做错了?
解决方案
推荐阅读
- java - 为什么优化的素数计数算法运行速度较慢
- html - 我在将 .css 文件中的 id 和类引用到 .html 文件时遇到问题
- networking - 网络只有登录后才能工作?
- angular - 角度如何将整数格式化为日期格式 hh/mm/ss
- node.js - 转译 .ts 源文件,无需依赖配置文件
- javascript - 您可以在 Javascript 中创建对对象数组的引用吗?
- python-3.x - 关于自动执行某些任务的问题
- swift - SwiftUI:单击按钮时如何呈现视图?
- c# - 使用属性值而不是枚举值将枚举序列化为 JSON
- android - 将 firebase 配置为使用 java 包而不是应用程序 ID