Send Push Notification on wordpress Comment Published with onesignal - php

using php to add action when there is a new comment in wordpress
i have tried this conditioning on a simple action and it works fine,
but here I get no results,
please someone else who understands better with this code, help me where did I go wrong,
is the problem a function within a function ? then what's the solution?
<?php
function notify_comment( $comment_id, $comment_approved ) {
if ( 1 == $comment_approved ) {
$comment = get_comment( $comment_id );
function sendMessages() {
$tujuan = $comment->comment_post_ID;
$permalink = get_permalink( $tujuan );
$posttitle = get_the_title( $tujuan );
$message = $comment->comment_content;
$judul = "$comment->comment_author Mengomentari=> $posttitle";
$logo = get_field('propil', $tujuan);
$content = array(
"en" => "$message",
"id" => "$message"
);
$headings = array(
"en" => "$judul",
"id" => "$judul"
);
$hashes_array = array();
array_push($hashes_array, array(
"id" => "read-more-button",
"text" => "Balas",
"icon" => "https://ppg-magetan-timur.id/wp-content/uploads/2023/02/balas.png",
"url" => "$permalink"
));
array_push($hashes_array, array(
"id" => "read-more-button-2",
"text" => "Baca komentar",
"icon" => "https://ppg-magetan-timur.id/wp-content/uploads/2023/02/lihat.png",
"url" => "$permalink"
));
$fields = array(
'app_id' => "bbcd3d4f-6965-4b73-b82a-*************",
'included_segments' => array(
'Test Segment'
),
'data' => array(
"foo" => "bar"
),
'contents' => $content,
'headings' => $headings,
'url' => "$permalink",
'chrome_web_image' => "$logo",
'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 NzJmMWRjZDMtMmI3Mi00NT****************'
));
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 = sendMessages();
$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");
}
}
add_action( 'comment_post', 'notify_comment', 10, 2 );
?>

<?php
function notify_comment( $comment_id, $comment_approved ) {
if ( 1 === $comment_approved ) {
$comment = get_comment( $comment_id );
$tujuan = $comment->comment_post_ID;
$permalink = get_permalink( $tujuan );
$posttitle = get_the_title( $tujuan );
$message = $comment->comment_content;
$judul = "$comment->comment_author Mengomentari=> $posttitle";
$logo = get_field('propil', $tujuan);
$end_point = 'https://api.webpushr.com/v1/notification/send/all';
$http_header = array(
"Content-Type: Application/Json",
"webpushrKey: 6361ccbba0dd06a67e9da0fa24d",
"webpushrAuthToken: 654"
);
$req_data = array(
'title' => "$judul",
'message' => "$message",
'target_url' => "$permalink",
'icon' => "$logo",
'action_buttons'=> array(
array('title'=> 'Balas', 'url' => "$permalink"),
array('title'=> 'Baca Lebih', 'url' => "$permalink")
)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $http_header);
curl_setopt($ch, CURLOPT_URL, $end_point );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($req_data) );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo $response;
}
}
add_action( 'comment_post', 'notify_comment', 10, 2 );
?>

Related

Firebase FCM server php-android

I created a simple php code to send a notification to my android devices which have google log in method from firebase implementation. Their tokens are already stored in my database. When I execute my php, it doesn't send the notification. Whoever , if i send a notification trough firebase notification console it works. This is my php code .
function sendGCM($message, $registration_ids) {
//FCM URL
$url = "https://fcm.googleapis.com/fcm/send";
//prepare data
$fields = array (
'registration_ids' => array ($registration_ids),
'data' => array ("message" => $message)
);
$fields = json_encode ( $fields );
//header data
$headers = array ('Authorization: key=<YOUR_API_KEY>', 'Content-Type: application/json');
//initiate curl request
$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_POSTFIELDS, $fields );
// execute curl request
$result = curl_exec ( $ch );
//close curl request
curl_close ( $ch );
//return output
return $result;
}
Error:
when I execute this php file, throw this error:
{
"multicast_id": 5359746182596118281,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "InvalidRegistration"
}
]
}
Try this:-
<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'your_key' );
$registrationIds = array($id); //$id is string not array
// prep the bundle
$notification = array
(
'title' => 'title',
'body' => 'body',
'icon' => 'logo',
'sound' => 'default',
'tag' => 'tag',
'color' => '#ffffff'
);
$data = array
(
'message' => 'message body',
'click_action' => "PUSH_INTENT"
);
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $notification,
'data' => $data,
'priority' => 'normal'
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
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 );
echo $result;
?>

Google Cloud Messaging returns Invalid Registration

When I am trying to send a gcm message through the below php, I get this error:
{"multicast_id":8958574426215974401,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
However, the server API key is exactly what Google gave me to use, and the gcm_token is accurately being stored to my database. I do not know where the issue lies.
Here is my server side php:
<?php
require 'db_connect.php';
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'AIzaSyREST OF MY KEY' );
//insert the message into a database
$sql = "SELECT gcm_token FROM users WHERE user_id='1' LIMIT 1;";
// preform
if (!mysqli_query($Thesisdb, $sql)) {
printf("Errormessage: ", mysqli_error($Thesisdb));
mysqli_close($Thesisdb);
} else{
$results = mysqli_query($Thesisdb, $sql);
$registrationIds = array($results);
// prep the bundle
$msg = array
(
'message' => '$user',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
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 );
echo $result;
}
?>
mysqli_query returns Boolen value (true or false) so this will not going to works directly.
we have to convert mysqli_query return values to array using fetch array, fetch assoc.
$results = mysqli_query($Thesisdb, $sql);
$registrationIds = array($results);
Code to combile all GCM Tokens.
registrationIds=array();
$sql="SELECT `user_id`,`push_notification_registration_id` FROM `tbl1` WHERE `user_status`='Active' AND `push_notification_registration_id`!=''";
$fire=mysqli_query($this->conn,$sql);
$users=array();
if( (isset($fire))&&(!empty($fire)) ){
while($result=mysqli_fetch_assoc($fire)){
array_push($users,$result);
}
}
foreach($users as $single_user){
$register_id=$single_user['push_notification_registration_id'];
array_push($registrationIds,$register_id);
}
$msg = array
(
'title' => $news_title,
'subtitle' => $news_description,
'tickerText' => 'Ticker Text',
'vibrate' => 1,
'sound' => 1,
'news_id' => $news_id,
'notification_type' => 'news'
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . YOUR_GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
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,true ) );
$result = curl_exec($ch );
curl_close( $ch );

GCM PHP : Field "data" must be a JSON array

I do know there are several posts here which talks about my issue but none works for me.Its either incomplete solution mentioned or left as is.
My query:
I am getting
Field "data" must be a JSON array: [{"sound":1,"vibrate":1,"message":"Push Notification Message","title":"Push Notification Title"}]
error when trying to use GCM. My regID, Sender ID, and server key looks fine.
May know how to resolve this.
PHP Code:
<?php
$to="";
if($_GET['id']){
$to = $_GET['id'];
}
$title="Push Notification Title";
$message="Push Notification Message";
sendPush($to,$title,$message);
function sendPush($to,$title,$message)
{
// API access key from Google API's Console
// replace API
define( 'API_ACCESS_KEY', 'API_HIDDEN');
$registrationIds = array($to);
$msg = array
(
'message' => $message,
'title' => $title,
'vibrate' => 1,
'sound' => 1
// you can also add images, additionalData
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => array($msg),
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
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 );
echo $result;
}
?>
Replace the line
$message="Push Notification Message";
by
$message=array( 'response' => json_encode("Push Notification Message"));
GCM requires the response data in JSONArray format.
OR Use below method
function sendGoogleCloudMessage( $data, $ids ) {
$apiKey = 'YOUR_KEY';
$url = 'https://android.googleapis.com/gcm/send';
$post = array(
'registration_ids' => $ids,
'data' => $data,
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );
$result = curl_exec( $ch );
if ( curl_errno( $ch ) ) {
$result = $result . 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
return $result;
}
and call it using
$response = array();
$response["title"] = "title";
$response["message"] = "Notification message.";
$data = array( 'response' => json_encode($response));
$result = sendGoogleCloudMessage($data, $ids);
It is working in my application.
Hope it'll help.

mismatch sender id in gcm using php

im getting mismatch senderid error.
in gcm, i double checked the sender id as client app project id and api_key.
My code is,
$ids = array( 'APA91bFDc......._p' );
$data = array( 'message' => 'Hello World!' );
$apiKey = 'AIzaSyA0_CFcI.........saGySJBE';
$url = 'https://gcm-http.googleapis.com/gcm/send';
$sender_id = '1063000000016';
$post = array(
'registration_ids' => $ids,
'data' => $data,
);
$headers = array(
'Authorization: key=' . $apiKey,
'Sender: id=' .$sender_id,
'Content-Type: application/json'
);
$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_POSTFIELDS, json_encode( $post ) );
$result = curl_exec( $ch );
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;
my response is
{"multicast_id":7107329859481637548,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
why i'm facing the problem?
I refered the previous questions like,
GCM Sender Id Mismatch, Android C2DM sender id, Unique SMS sender id? and etc
edit
I just added the sender id myself to the headers. where to mention the sender id and how to mention in php

Add custom fields to a new wordpress post using the wordpress API

I need to programmatically create new Wordpress posts and assign custom fields to each. Using the Wordpress xmlrpc API, I can successfully add a new post, but the custom fields are not added.
Here's an excerpt of the code:
$blogid = 0;
$username = 'user';
$password = 'xyzzy1234';
$method = 'wp.newPost';
$title = "Post Title";
$pcontent = "I'm the post content.";
$categories = array('Cat 1', 'Cat 2');
$post_status = 'publish';
$custom_fields = array('cccId' => '12345', 'cccType' => 'news');
$content = array(
'post_type' => 'post',
'post_status' => $post_status,
'post_title' => $title,
'post_content' => $pcontent,
'terms_names' => array('category'=>$categories),
'comment_status' => $comment_status,
'ping_status' => $ping_status,
'custom_fields' => $custom_fields
);
$parameters = array($blogid, $username, $password, $content);
$response = sendRequest($method, $parameters);
function sendRequest($methodName, $parameters) {
$request = xmlrpc_encode_request($methodName, $parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, RPC_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
$results = print_r(xmlrpc_decode($results));
curl_close($ch);
return $results;
}
After some experimentation, it turns out that $custom_fields needs to be specified like this:
$custom_fields = array(
array('key' => 'cccId', 'value' => '12345'),
array('key' => 'cccType', 'value' => 'news')
);

Categories