du7999 2018-12-31 21:21 采纳率: 100%
浏览 55

从我的提供商(PHP)服务器向iOS设备发送推送通知

I'm currently in the process of setting up a provider server to send out push notifications to iOS devices with my app installed.

I'm struggling to find any recent versions of working examples but have put the following together. I'm getting no errors returned but the push notification isn't showing up on my test device.

I can confirm the latest device token is being used and the .pem cert is valid.

Any help on this would be greatly appreciated.

Best regards, J

$apnsHost = 'api.sandbox.push.apple.com';
$apnsCert = '/cert.pem';
$apnsPort = 2197;
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
$payload['aps'] = array(
    'alert' => array(
        'title' => 'Sample push number ' . mt_rand(100, 999),
        'body' => 'Sample push body goes here'
    ),
    'badge' => 9,
    'sound' => 'default',
    'my_value_1' => 'more data',
    'my_value_2' => 'even more data'
);

// JSON-encode payload
$output = json_encode($payload, JSON_NUMERIC_CHECK);

// Cancel if payload too long
if(strlen($output) > 2048){
    die('Payload too long ('.strlen($output).'): Aborted');
}

// Build the binary notification (correctly)
$token = '185e522cd0e3f35f09sdg398f25fe28038f6a0743339b0a378'; 
$apnsMessage = chr(0).pack('n', 32).$token.pack('n', strlen($output)).$output;

// Send it to the server
$result = fwrite($apns, $apnsMessage, strlen($apnsMessage));

// Result returns number of bytes sent on success, false otherwise
if(intval($result) > 0){
    // Push sent
    $response = $result.' bytes sent. $payload size is: '.strlen($output).' (payload limit is 2048 bytes)';
    fclose($apns);
}else{
    // Push failed
    $error = error_get_last();
    $response = (is_array($error) ? $error['message'] : 'undefined error');
}

// Show result
die($response);

Output: 240 bytes sent. $payload size is: 171 (payload limit is 2048 bytes)

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 R语言Rstudio突然无法启动
    • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
    • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值