在线文档:Generating a remote notification | Apple Developer Documentation
首先,你需要一些必要的资源来进行推送:
A.获取 APNs 认证密钥
- 登录 Apple 开发者账户:Apple Developer.
- 在 Certificates, Identifiers & Profiles 页面,创建一个 Apple Push Notification Service (APNs) 认证密钥,并下载
.p8
文件。确保记录下 Key ID、Team ID 和 Bundle ID。
B.获取设备的 device token
你需要从客户端(iOS 应用)获取 设备的 device token
,这是推送目标设备的唯一标识符。
C.安装Jwt
composer require firebase/php-jwt
// 配置认证密钥
$authKey = BASE_ROOT_PATH . '/data/push/XXXXXXXXX.p8'; // 认证密钥路径(.p8 文件)
// 生成 JWT token
$issuedAt = time();
$expirationTime = $issuedAt + 3600; // 1小时有效期
$payload = [
'iss' => $config['appId'], // Apple Team ID
'iat' => $issuedAt, // 当前时间
'exp' => $expirationTime, // 过期时间
'aud' => 'appstoreconnect-v1',
'sub' => $config['appKey'] // 你的 Key ID
];
// 生成 JWT token
$privateKey = file_get_contents($authKey);
$authToken = JWT::encode($payload, $privateKey, 'ES256',$config['appKey']);
// 发送推送请求
$url = "https://api.push.apple.com:443/3/device/{$regId}";
$bundleId = self::PACKAGE_NAME; // 你的应用的 Bundle ID
// 创建请求头
$headers = [
"Authorization: Bearer {$authToken}",
"Content-Type: application/json",
"apns-topic: {$bundleId}"
];
// 推送数据
$data = [
'aps' => [
'alert' => [
'title' => $title,
'body' => $body,
],
'badge' => 1,
'sound' => 'default',
'mutable-content' => 1,
]
];
if(!empty($image)){
$data['media-url'] = $image;
}
if(!empty($custom)){
$data['customData'] = $custom;
}
$re = self::_Curl($url, json_encode($data), $headers, "POST");
$res = json_decode($re, true);