Here’s a single php file where you can send a push notification using your OneSignal account via REST API. It’s simple and straightforward using the code example at OneSignal.com. This one is more complete as the code example is just the curl_setopt code. But what if you don’t know how to POST the code from your form to send a message using the basic example from OneSignal REST API? Example in this link are all just API parameters with basic code example, no actual code example with an HTML form that will work if you copy paste it.
If you want a quick way to send notification from an external web form without logging in to your OneSignal account, then this form is for you. It’s pretty basic, you can add more parameters if you want to and it’s very easy to understand, even if you’re not an expert code like me.
You can modify the form and just add your APP ID and REST API KEY, and it will work in a snap!
Below is the single php file web form to send push notifications via OneSignal REST API.
[php light=”true”]
<html>
<head>
<title>Push Notification Sender</title>
</head>
<body>
<form action="sendpush.php" method="post">
<input type="text" name="heading"><br>
<textarea name="message"></textarea><br>
<input type="hidden" name="app_id" value="APP_ID_HERE">
<input type="submit" name="send_all" value="Send">
</form>
</body>
</html>
<?php
if (isset($_POST[‘send_all’])) {
$app_id = $_POST[‘app_id’];
$heading = $_POST[‘heading’];
$message = $_POST[‘message’];
$response = sendMessage($app_id, $heading, $message);
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
}
function sendMessage($app_id, $heading, $message) {
$content = array(
"en" => $message
);
$headings = array(
‘en’ => $heading
);
$fields = array(
‘app_id’ => $app_id,
‘included_segments’ => array(
‘All’
),
‘data’ => array(
"foo" => "bar"
),
‘contents’ => $content,
‘headings’ => $headings
);
$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_HERE’
));
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;
}
?>
[/php]
Just create a single php file and name it sendpush.php. If you want a different name, then just edit the php file name in line 7 of the code inside form div.
That’s all. Pretty basic and I’m pretty sure you can make it work. This is literally what we call spoon feeding. But you’ll learn from it as it’s just a few lines of code and it’s very easy to understand.
Leave a Reply