I created a custom module for Drupal 8. I made a hook that is to detect whenever a new node is created, then send a notification to a subscriber. The code I have is this:
<?php
/**
* #file
* Contains onesignal_api.module.
*
*/
use Drupal\Core\Entity\EntityInterface;
/***
* Hook into OneSignal API to send push notifications once a new node is created
*/
function onesignal_api_insert(\Drupal\Core\Entity\EntityInterface $node) {
if($node->isNew()) {
function sendMessage() {
$content = array(
"en" => 'New Node Created'
);
$hashes_array = array();
array_push($hashes_array, array(
"id" => "like-button",
"text" => "Like",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "http://push-test/"
));
array_push($hashes_array, array(
"id" => "like-button-2",
"text" => "Like2",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "http://push-test/"
));
$fields = array(
'app_id' => "XXXXXXXXX",
'include_player_ids' => array("XXXXXX","XXXXX","XXXXXX"),
'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 XXXXXXX'
));
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");
}//if Node is new
}//func hook signal
Is there something that I need to change to get this to work? all of the code inside of the if statement works outside of the if statement.
You probably want to implement hook_node_presave.
It acts on a node being created or updated before it is saved to the database :
function onesignal_api_node_presave(\Drupal\Core\Entity\EntityInterface $node) {
if ($node->isNew()) {
// $node is about to be created...
}
}
#see hook_ENTITY_TYPE_presave
Please look below code and add your code as per your requirements.
function onesignal_api_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getEntityType()->id() == 'node') {
switch ($entity->bundle()) {
case 'content-type-name': // if multiple entities
}
}
}
Related
I set up an entity hook in Drupal 8 to leverage the API and send push notifications if a new node in Drupal is created. I have the hook set up in the OneSignalConfigForm.php file of the OneSignal integration module for Drupal 8, but when I create a new node, no notification comes up as expected. Here is the code:
namespace Drupal\onesignal_api\Controller;
use Drupal\Core\Modules\Node\NodeAPI;
class OneSignalApiController extends NodeAPI { function function hook_onesignal_api_insert(Drupal\Core\Node\NodeAPI $node){
if($node->is_new) {
function sendMessage() {
$content = array(
"en" => 'New Node Created'
);
$hashes_array = array();
array_push($hashes_array, array(
"id" => "like-button",
"text" => "Like",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "http://push-test/"
));
array_push($hashes_array, array(
"id" => "like-button-2",
"text" => "Like2",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "http://push-test/"
));
$fields = array(
'app_id' => "8573c047-12f2-496c-a202-5942951cdda8",
'include_player_ids' => array("935d651a-a3f7-49eb-9e1b-23d8ca828764","4f536f45-f14f-45d5-aff0-56292a388cec","6f3c36d8-c3c9-4f99-9fde-c61590eea605"),
'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 N2E4ODA5YjItNjViNS00YmVkLThjMWItYTljODhhNjI0YjFj'
));
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");
}
}
Is there anything else I'm missing?
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");
I am trying to send user-specific web notifications with onesignal and i solved everything except this variable null problem.
I use that variable multiple times and there is no problem except these lines:
<?php
if(isset($_POST["sub"]))
{
$my_variable= $_POST["t1"];
$SQL = "some sql here";
if (mysqli_query($db, $SQL)) {
echo $my_variable;
echo "<br>";
function sendMessage(){
$content = array(
"en" => 'test message'
);
$fields = array(
'app_id' => "5b0eacfc-3ac8-4dc6-891b-xxxxx",
'filters' => array(array("field" => "tag", "key" => "key", "relation" => "=", "value" => "$my_variable")),
'data' => array("foo" => "bar"),
'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 xxxxxxx'));
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);
The result is :
1 JSON sent: {"app_id":"5b0eacfc-3ac8-4dc6-891b-xxxxx","filters":[{"field":"tag","key":"key","relation":"=","value":"null"}],"data":{"foo":"bar"},"contents":{"en":"test message"}}
I tried so many variations with/without quotas , json_encode() function but couldn't pass that variable to that array.
Your variable is out of scope.
You define $my_variable outside of the function sendMessage(), but proceed to try and use it within the function, without passing it as a parameter.
This can be fixed with the following:
function sendMessage($filterValue)
{
$content = array(
"en" => 'test message'
);
$fields = array(
'app_id' => "5b0eacfc-3ac8-4dc6-891b-xxxxx",
'filters' => array(array("field" => "tag", "key" => "key", "relation" => "=", "value" => $filterValue)),
'data' => array("foo" => "bar"),
'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 xxxxxxx'));
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($my_variable);
$return["allresponses"] = $response;
$return = json_encode( $return);
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;
}
In my gcm android app I am sending 2 types of messages from application server.I got the idea about what is collapse key, but Idont know how to use.These are the two types of messages.
1.
$message = array(
"price" => "signal",
"type" => $user_type,
"date" => $date1,
"name" => $signal_name,
"buy" => $price,
"stop" => $stop,
"tv" => $trig_value,
"tp" => $profit,
"res" => $result,
);
second one
$message = array(
"price" => "instru",
"price1" => $trade1,
"price2" => "$trade2",
"price3" => "$trade3",
"price4" => "$trade4",
"price5" => "$date"
);
What I need is the last messages send for both of the message types persist in gcm server.How can I do that.I am giving the gcm class also .Please help.
GCM.php
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key='.GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
You should add the collapse_key parameter to your JSON.
The JSON should look like this :
For example, for the first type :
{
"registration_ids":["...", "..."],
"collapse_key": "type1",
"data": {
"price" => "...",
"type" => "...",
...
},
}
For the second type, give a different value to collapse_key.
Based on your code and my limited knowledge of PHP, you need something like this :
$fields = array(
'collapse_key' => $collapse_key,
'registration_ids' => $registatoin_ids,
'data' => $message,
);
And the $collapse_key should be initialized based on the type of data you have in $message.