APNs 提供程序 API 批处理请求


APNs Provider API batch request

我即将用PHP重写我的推送服务,以使用新的APNs Provider API。我的问题是,是否有向多个设备发送一个通知的最佳实践......

我已经找到了使用 PHP 发送推送通知的解决方案:

$ch = curl_init("https://api.development.push.apple.com/3/device/$device_token");
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"aps":{"alert":"Here I am","sound":"default"}}');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("apns-topic: $apns_topic"));
curl_setopt($ch, CURLOPT_SSLCERT, $pem_file);
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $pem_secret);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

但是使用此代码,我可以将消息发送到一台设备,因为我必须将设备令牌放在 URL 中。但是我想将消息发送到未知数量的设备。不幸的是,我找不到用于向多个设备发送消息的端点。


苹果文档(https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html)是这样说的:

通过多个通知保持与 APNs 的连接处于打开状态;不要重复打开和关闭连接。APNs 将快速连接和断开连接视为拒绝服务攻击。

所以我认为把我的CURL request放进一个for-loop,然后遍历我所有的设备令牌是不好的做法。

有人对如何解决此案有任何建议吗?

提前谢谢。

不确定 curl,但一般来说,Apns 提供商必须保持与 Apns Cloud 的持久连接。无法使用单个消息向多个设备广播。APNS 提供程序应利用 http/2(每个连接多个流),还可以跨多个连接发送消息,但不得在循环中进行连接和断开连接,这将被视为 DoS 攻击。

避免连接循环,

您应该在循环中发布消息,连接/断开连接部分不得是循环的一部分。

我希望它有所帮助。

问候_Ayush

libcurl 会尽可能自动尝试保持连接打开。要遵循的模式是执行以下操作:

1) 创建卷曲手柄:$ch = curl_init();

2) 在手柄上设置适当的选项:

curl_setopt($ch, CURLOPT_POSTFIELDS, '{"aps":{"alert":"Here I am","sound":"default"}}');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("apns-topic: $apns_topic"));
curl_setopt($ch, CURLOPT_SSLCERT, $pem_file);
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $pem_secret);

3) 开始 for 循环,为每个收件人设置 url 并执行请求:

for ($tokens as $token) { //Iterate push tokens
    $url = "https://api.development.push.apple.com/3/device/{$token}";
    curl_setopt($ch, CURLOPT_URL, $url);
    $result = curl_exec($ch);
    // Check result, handle errors etc...
   }
   curl_close($ch); // Close connection outside the loop

遵循上述方法应保持连接打开并符合Apple的要求。