通过 cURL/PHP 发送时设备上未收到 Firebase 通知

我有一个 iOS 应用,该应用已在应用商店上线.我可以将推送通知发送到安装了该应用的 iOS 设备,但前提是我从 Firebase 控制台发送它们.

I have an iOS app which is live on the app store. I am able to send push notifications to iOS devices which have the app installed, but only when I send them from the Firebase console.

当我尝试通过 cURL 请求发送推送通知时,来自服务器的响应表明我成功了,但设备上没有收到消息.我已经尝试过使用多播和单个接收者有效负载.

When I try to send push notifications via a cURL request, the response from the server indicates that I was successful but the message isn't received on the device. I have tried this with both multicast and single recipient payloads.

我一定遗漏了一些更基本的东西,但我看不到它.

I must be missing something more fundamental, but I can't see it.

这是我的 PHP 代码:

Here is my PHP code:

<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'AI*****4LPGkx8xtDG2tBl*****7KWJfmp1szcA' );
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
    'message'   => 'here is a message. message',
    'title'     => 'This is a title. title'
);
$fields = array
(
    'to'            => "cUxd-iTVVWo:APA*****kQTuqJ5RREKhhlJjm27NCuVfUn5APg3lBFqh-YWjgx*****iOpAQeLB14CzM2YTwIJo_75jzCmbFLKj0_zpKSHvAEbmJz*****BBezGJIng-N4H-cAD6ahY7mQNYZtEJLAIE",
    'data'          => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;

这是我在运行此代码时得到的响应:

Here is the response I get when running this code:

{"multicast_id":5814921248239922706,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1476193002715692%a4ddee3cf9fd7ecd"}]}

{"multicast_id":5814921248239922706,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1476193002715692%a4ddee3cf9fd7ecd"}]}

推荐答案

有两个问题:

  1. 我需要在有效负载中包含 notification 部分,而不是 data
  2. 不知何故,负载没有被 PHP 正确格式化.

最后,我使用 PHP 函数 shell_exec() 通过 SSH 执行 cURL 请求.这并不理想,但它完成了工作.

In the end I used the PHP function shell_exec() to do a cURL request over SSH instead. This isn't ideal but it got the job done.

示例代码:

shell_exec('curl -X POST --header "Authorization: key=<key here>" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{"to":"'.$to.'","priority":"high","notification":{"body": "'.stripslashes($message).'"}}"');

相关文章