How to Send push notifications using One Signal + PHP + Server API? - php

I am using one signal to send push notification for android app. My question is
How Can I setup send push notifications using server rest api?

<?PHP
function sendMessage(){
$content = array(
"en" => 'Testing Message'
);
$fields = array(
'app_id' => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx",
'included_segments' => array('All'),
'data' => array("foo" => "bar"),
'large_icon' =>"ic_launcher_round.png",
'contents' => $content
);
$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 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'));
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);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>

You can always refer to the official docs:
https://documentation.onesignal.com/reference#section-example-code-create-notification
'app_id' is currently known as (OneSignal App ID) in the OneSignal
Settings->Keys and IDs
in 'Authorization: Basic xxx...' past the "REST API Key" just below the App ID

I see you have set isAndroid=true, but OneSignal is returning an error that shows that the application with ID eec33e8e-5774-4b74-9aae-37370778c4b2 does not have Android notifications enabled.
Make sure your app ID is correct, and if it is, that Android notifications are enabled in your OneSignal settings.

$to - Device ID
$title - Notification Title
$message - Notification Message
$img - Full image link
Usage:
sendnotification($to, $title, $message, $img);
With Demo Values :
sendnotification("Device_ID","Test Notification","Test Message","https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png");
function sendnotification($to, $title, $message, $img)
{
$msg = $message;
$content = array(
"en" => $msg
);
$headings = array(
"en" => $title
);
if ($img == '') {
$fields = array(
'app_id' => 'YOUR_APP_ID',
"headings" => $headings,
'include_player_ids' => array($to),
'large_icon' => "https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png",
'content_available' => true,
'contents' => $content
);
} else {
$ios_img = array(
"id1" => $img
);
$fields = array(
'app_id' => 'YOUR_APP_ID',
"headings" => $headings,
'include_player_ids' => array($to),
'contents' => $content,
"big_picture" => $img,
'large_icon' => "https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png",
'content_available' => true,
"ios_attachments" => $ios_img
);
}
$headers = array(
'Authorization: key=**APP_KEY**',
'Content-Type: application/json; charset=utf-8'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/notifications');
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);
return $result;
}

Related

Adding OneSignal segments to filters array

I am using following PHP script to send OneSignal push notifications to subscribed devices.
<?PHP
function sendMessage(){
$content = array(
"en" => 'Testing Message desde el backend small icon '
);
$fields = array(
'app_id' => "xxxx",
'filters' => array(array("field" => "tag", "key" => "correo", "relation" => "=", "value" => "xxx")),
'data' => array("foo" => "bar"),
'small_icon' =>"ic_push",
'contents' => $content
);
$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 xxxxx'));
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);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
This script is working fine, and the notifications are sent.
Now I need to add more filters, for example I need to add a filter to two other segments that I have created at the OneSignal dashboard.
The segments are "skateboard" and "administrators".
How can I add these two segment to the filters array?
You need to pass segments name array in fields like you are passing tags.
$content = array(
"en" => 'Notification Message Here..'
);
$heading = array(
"en" => 'Heading goes here..'
);
$fields = array(
'app_id' => 'XXXXXXXXXXXXXXXXXXXXX',
'contents' => $content,
'headings' => $heading,
'included_segments' => array('SegmentName1','SegmentName2'),
'tags' = array(array("key" => "state", "relation" => "=", "value" => 'Delhi'))
);
$fields = json_encode($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 XXXXXXXXXXXXXXXXXXX'));
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;

How can I create a button to send notifications to OneSignal?

Is it possible to create a button whose click will send my users notifications on their Android app from my PHP website. I already have a OneSignal account attached to my app. I just want to send it from my website, not through OneSignal dashboard.
You can do it using OneSignal REST API.
Here is an example extracted from OneSignal REST API Docs:
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' => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
'included_segments' => array(
'All'
),
'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 NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj'
));
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 set custom title message in web push notification

i have integrated one-signal in my web application, notifications are working fine but if considering web page title in push notification title.
i need to set it custom title in my push notification.
i need to set custom message in place of "Dashboard"
Here is my code:
$content = array(
"en" => 'Hello Hii..!!'
);
$fields = array(
'app_id' => 'APP_ID',
'include_player_ids' => ['ids'],
'data' => array("foo" => "bar"),
'url' => 'URL',
'contents' => $content
);
$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 AuthorizationKey';
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;
set heading in your fields array
$content = array(
"en" => 'Your message..!!'
);
$heading = array(
"en" => "Your custom title message"
);
$fields = array(
'app_id' => 'YOUR_APP_ID',
'include_player_ids' => [ids],
'data' => array("foo" => "bar"),
'url' => 'http://www.yoursite.com',
'contents' => $content,
'headings' => $heading
);
Use this one as mention bellow
public function sendPush($players_id,$massage,$data,$heading){
// $players_id your device id where you want to push
$data1[]=$players_id;
//message for your push
$content = array(
"en" => $massage
);
// if you want to send data in for of JSON or some values
$data_response=array(
"value" => $data
);
//you can add heading through this
$heading = array( "en" => $heading);
// print_r($cat_data);
$fields = array(
'app_id' => 'YOUR_APP_ID',
'include_player_ids' => $data1,
'contents' => $content,
'headings' => $heading,
'data' =>$data_response
);
$fields = json_encode($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 YOUR_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 $response;
}

Sending Firebase notification with PHP

everyone! I am having a problem using PHP to send FIrebase notification. When I send it from Firebase console, I get the notification, but when I send it from PHP, I don't receive any notification.
DO you have any idea what is the problem?
Here is my PHP code:
<?php
$message = 'ojlaasdasdasd';
$title = 'ojla';
$path_to_fcm = 'https://fcm.googleapis.com/fcm/send'; $server_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5LnDZO2BpC2aoPMshfKwRbJAJfZL8C33qRxxxxxxxxxxxxL6';
$key = 'eqnlxIQ1SWA:APA91bGf1COAZamVzT4onl66_lEdE1nWfY7rIADcnt9gtNYnw7iWTwa7AYPYTHESFholkZ89ydCQS3QeL-lCIuiWTXiqoDREO0xhNdEYboPvqg8QsBYkrQVRlrCLewC4N-hHUja1NG4f';
$headers = array(
'Authorization:key=' .$server_key,
'Content-Type: application/json');
$fields = array
(
'to' => $key,
'notification' => array('title' => $title,'body' => $message)
);
$payload = json_encode($fields);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, '$path_to_fcm' );
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_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt( $ch,CURLOPT_POSTFIELDS, $payload);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
?>
I don't get any echo from the server
try this code.Its working fine for me.just change key and token
<?php
define('API_ACCESS_KEY','Api key from Fcm add here');
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$token='235zgagasd634sdgds46436';
$notification = [
'title' =>'title',
'body' => 'body of message.',
'icon' =>'myIcon',
'sound' => 'mySound'
];
$extraNotificationData = ["message" => $notification,"moredata" =>'dd'];
$fcmNotification = [
//'registration_ids' => $tokenList, //multple token array
'to' => $token, //single token
'notification' => $notification,
'data' => $extraNotificationData
];
$headers = [
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
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($fcmNotification));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
I use the following function to send a HTTP Request to Firebase:
function request($url, $body, $method = "POST", $header = "Content-type: application/x-www-form-urlencoded\r\n")
{
switch ($method) {
case 'POST':
case 'GET':
case 'PUT':
case 'DELETE':
break;
default:
$method = 'POST';
break;
}
$options = array(
'http' => array(
'header' => "$header",
'method' => "$method",
'content' => $body
)
);
$context = stream_context_create($options);
$data = file_get_contents($url, false, $context);
$data = json_decode($data, true);
return $data;
}
To execute the function I use the following code:
$fcm_key = "";
$body = array("data" => $data, "to" => "$fcm_token");
$body = json_encode($body);
$json = request("https://fcm.googleapis.com/fcm/send", $body, "POST", "Authorization: key=$fcm_key\r\nContent-Type:application/json");
For me, this code works without any problems. Be sure that you use the right FCM device token ($fcm_token) and set the right FCM key ($fcm_key).
$tokenID = $valueTwo["TokenID"];
$cmMessage = array();
$cmMessage["type"] = 3;
$cmMessage["receiverMail"] = $receiverMail;
$cmMessage["ownerMail"] = $ownerMail;
$cmMessage["jsonData"] = $jsonData;
$url = "https://fcm.googleapis.com/fcm/send";
$title = "";
$body = "";
//$notification = array('title' => $title, 'body' => null, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $tokenID, 'priority' => 'high', 'data' => $cmMessage);
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key=' . $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
Get your server key and token id to send write them... Dont use notification tag...Like I did in code... Cuz if you write notification tag, Application in background is not got receive msg Cuz notification tag executes on foreground and in background automatic notification is displayed..
Send firebase push notification via php to android, ios
function sendPushNotification($to = '', $data = array()){
$api_key = '';
$fields = array('to' => $to, 'notification' => $data);
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$api_key
);
$url = 'https://fcm.googleapis.com/fcm/send';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
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);
if ($result === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$to = ''; //Device token
// You can get it from FirebaseInstanceId.getInstance().getToken();
$message = array(
'title' => 'Hai',
'body' => 'New Message');
echo sendPushNotification($to, $message);

Onesignal-php to android

I have this php script:
<?php
function sendMessage(){
$content = array(
"en" => 'text message test'
);
$fields = array(
'app_id' => "XXXXXX",
'included_segments' => array('All'),
'data' => array("foo" => "bar"),
'headings' => array("en" => "Test message!!"),
"isAndroid"=>true,
// 'android_group' => 'Tanks',
// 'android_group_message' => array("en" => "message"),
'contents' => $content
);
$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',
'Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'));
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();
?>
But is doesn't end notifactions to android users. Is there a example to send pushnotifications from php over OneSignal to android devies?
Well, i did not add my one sognal authentication code ;)

Categories