Create Onesignal Push Notification in PHP
01-02-2018To send onesignal notification in Php, we can use following codes:
function sendMessage($title, $message, $userId, array $extraParams, bool $isTest = false)
{
$app_id = "b21eaaf8-7da9-44e4-aa39-920e2503a109";
$rest_api_key = "NWEwMjU1YmItYzVmNy00YgBhLTlhNjEtNmZlMmUzOWU0Y2Ey";
$heading = array(
"en" => $title
);
$content = array(
"en" => $message
);
$fields = array(
'app_id' => $app_id,
'data' => $extraParams,
'contents' => $content,
'headings' => $heading
);
$fields['large_icon'] = 'http://www.hurdatakip.com/resources/assets/images/icon.png';
if ($userId != null) {
$fields['filters'] = array(
array(
'field' => 'tag',
'key' => 'userId',
'relation' => '=',
'value' => $userId
)
);
}
if ($isTest) {
$fields['included_segments'] = array("Test Users");
} else {
$fields['included_segments'] = array("All");//You can specify other segments like Active Users, Inactive Users
}
$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 ' . $rest_api_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["allresponses"] = $response;
$return = json_encode($return);
print("\n\nJSON received:\n");
print($return);
print("\n");
}
Note: We should create Test Users segment in Onesignal admin panel.