php实现ios推送
PHP 实现 iOS 推送
要实现 iOS 推送通知,需要使用 Apple Push Notification Service (APNS)。以下是实现步骤和代码示例:

获取必要的证书和密钥
从 Apple Developer 账户生成推送证书(.pem 文件)或使用基于 Token 的认证(.p8 文件)。确保证书或密钥与 App Bundle ID 匹配。
安装依赖库
推荐使用 php-apns 或直接通过 cURL 发送请求。若使用 Token 认证,需 JWT 库生成令牌:
composer require lcobucci/jwt
使用 cURL 发送推送(基于证书)
$deviceToken = 'DEVICE_TOKEN_HERE';
$message = '推送消息内容';
$certificatePath = 'path/to/cert.pem';
$passphrase = '证书密码';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $certificatePath);
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195',
$err,
$errstr,
60,
STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT,
$ctx
);
if (!$fp) {
echo "Failed to connect: $err $errstr";
return;
}
$payload = json_encode([
'aps' => [
'alert' => $message,
'sound' => 'default'
]
]);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
fclose($fp);
使用 Token 认证(HTTP/2 API)
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Ecdsa\Sha256;
$keyId = 'KEY_ID_FROM_APPLE';
$teamId = 'APPLE_TEAM_ID';
$bundleId = 'APP_BUNDLE_ID';
$deviceToken = 'DEVICE_TOKEN_HERE';
$privateKey = InMemory::file('path/to/AuthKey_XYZ.p8');
$config = Configuration::forSymmetricSigner(new Sha256(), $privateKey);
$now = new DateTimeImmutable();
$token = $config->builder()
->issuedBy($teamId)
->issuedAt($now)
->withHeader('kid', $keyId)
->getToken($config->signer(), $config->signingKey());
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_setopt($ch, CURLOPT_URL, 'https://api.sandbox.push.apple.com/3/device/' . $deviceToken);
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'apns-topic: ' . $bundleId,
'authorization: bearer ' . $token->toString(),
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'aps' => ['alert' => 'Hello from PHP!', 'sound' => 'default']
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
注意事项
- 开发环境使用
gateway.sandbox.push.apple.com,生产环境用gateway.push.apple.com。 - Token 认证需每 60 分钟更新 JWT。
- 错误处理需检查 HTTP 状态码和响应体(如
{"reason":"BadDeviceToken"})。 - 负载支持自定义字段(如
{'aps': {...}, 'custom_key': 'value'})。







