我想使用 PHP 向特定用户发送推送通知。 能够通过 OneSignal 向所有用户发送推送通知,但无法向特定用户发送推送通知。 已使用 Web 视图创建 Android 应用程序 根据文档,它需要设备 ID,但不知道通过 php 获取。
1> 是否需要为我的应用程序添加另一个库来推送通知。 2> 如何通过php获取推送通知所需的设备ID 3> 如何针对特定用户进行推送通知
框架:Laravel 应用程序:安卓
<?PHP
function sendMessage() {
$content = array(
"en" => 'English Message'
);
$hashes_array = array();
array_push($hashes_array, array(
"id" => "like-button",
"text" => "Like",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "https://yoursite.com"
));
array_push($hashes_array, array(
"id" => "like-button-2",
"text" => "Like2",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "https://yoursite.com"
));
$fields = array(
'app_id' => "my_app_id",
'included_segments' => array(
'Subscribed Users'
),
'data' => array(
"foo" => "bar"
),
'contents' => $content,
'web_buttons' => $hashes_array
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Authorization: Basic Auth Key'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode($return);
$data = json_decode($response, true);
print_r($data);
$id = $data['id'];
print_r($id);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
Onesignal 文档 https://documentation.onesignal.com/reference/create-notification
根据他们的 API 文档 ...可以发送到不同的段:
EMAIL
、USER TAG
、TEST USERS
。他们的示例代码提示filters
(不存储令牌时唯一的选择):
$fields = [
...
'filters' => [
["field" => "external_user_id" "relation" => "=", "value" => $user->id]
]
];
他们的常见问题解答还包含您的问题:
如何向单个用户发送通知?
在 PHP 中这不应该有任何不同,虽然它清楚地提示“您的数据库”(Eloquent
Model
),它应该能够将 int $user_id
翻译为 string
或 string[]
$registration_id
又名设备注册令牌。这意味着您的 MessagingService
实现需要告诉 Laravel API 他们当前的令牌 - 否则发送时这些将是未知的。
我宁愿用 Java 回答 PHP 问题:
.setExternalUserId()
设置 Laravel int $user_id
。当使用external_user_id
作为过滤条件时,还应该设置身份验证。
通常可以选择存储令牌,然后再次查找它们
...或使用
.setExternalUserId()
,然后可以将其用作过滤条件。
移动客户端必须传递其令牌 - 或者是
int $user_id
/ string $email
。