I am trying to use gcm in appengine using PHP runtime. Following is the code, which uses URLFetch service
$context = array("https"=>
array( "method" => "post",
"content" => json_encode($fields),
"header" => "Content-Type: application/json\r\n" .
"Authorization: key=" . GOOGLE_API_KEY . "\r\n"
)
);
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
Following is the Original code that uses PHP Curl:
$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);
PHP code that uses Curl works well, but the code that uses urlfetch service of appengine does't work. Can someone tell me where am I doing wrong.
This is tested code.
public function sendAndroidPushNotification($registration_ids, $message)
{
// Adding devicetoken in array
$registrationIds = array($registration_ids);
$msg = array(
'message' => $message,
'title' => 'notification center',
'tickerText' => $message,
'vibrate' => 1,
'sound' => 1,
);
$fields = array(
'registration_ids' => $registrationIds,
'data' => $msg
);
$fields = json_encode($fields);
$arrContextOptions=array(
"http" => array(
"method" => "POST",
"header" =>
'Authorization: key = '. "\r\n" .
'Content-Type: application/json'. "\r\n",
"content" => $fields,
),
"ssl"=>array(
"allow_self_signed"=>true,
"verify_peer"=>false,
),
);
$arrContextOptions = stream_context_create($arrContextOptions);
$result = file_get_contents('https://android.googleapis.com/gcm/send', false, $arrContextOptions);
return $result;
}
Related
I get notifications on Android but when I send the notification to an IOS device, it doesn't get received, even though it says success.
I added badges, sound, vibration, priority.. etc but none of this solved the problem.
function sendNotification($title, $body, $aid,$destination)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$message = array(
'title' => $title,
'body' => strip_tags($body),
'vibrate' => 1,
'sound' => 1,
"action" => "url",
'sound' => 'default',
'badge' => '1',
'priority'=>'high',
"action_destination" => $destination,
);
$fields = array(
'registration_ids' => $aid,
'data' => $message
);
$headers = array(
'Authorization: key=KEYHERE',
'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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
}
The mobile developer says that theres a new firebase update and I frankly think hes bsing... Can someone explain to me whats going on? I think my part here is done, but you guys might see something wrong with my code...
I am using below script to send notification to particular users:
<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'My_API_KEY' );
$registrationIds = array( TOKENS );
// prep the bundle
$msg = array
(
'body' => "abc",
'title' => "Hello from Api",
'vibrate' => 1,
'sound' => 1,
);
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $msg
);
$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;
?>
Script is working fine but how can i send notification to all user who installed my app. I created a topic in my app (alerts), and i can send notification to all users via firebase console. Can anyone guide me to update above script for topic.
I fixed by replacing
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $msg
);
To
$fields = array
(
'to' => '/topics/alerts',
'notification' => $msg
);
You can send the notifications without curl (which was not available on my server).
I prepared a function which can send a notification to a specified topic:
sendNotification("New post!", "How to send a simple FCM notification in php", ["new_post_id" => "605"], "new_post", "YOUR_SERVER_KEY");
function sendNotification($title = "", $body = "", $customData = [], $topic = "", $serverKey = ""){
if($serverKey != ""){
ini_set("allow_url_fopen", "On");
$data =
[
"to" => '/topics/'.$topic,
"notification" => [
"body" => $body,
"title" => $title,
],
"data" => $customData
];
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n" .
"Authorization:key=".$serverKey
)
);
$context = stream_context_create( $options );
$result = file_get_contents( "https://fcm.googleapis.com/fcm/send", false, $context );
return json_decode( $result );
}
return false;
}
i am work with google firebase many time and i suggest my simple code for send notification on topic.
public function test()
{
// Method - 1
// $fcmUrl = 'https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1';
// $notification = [
// "message" => [
// "topic" => "foo-bar",
// "notification" => [
// "body" : "This is a Firebase Cloud Messaging Topic Message!",
// "title" : "FCM Message",
// ]
// ]
// ];
// Method - 2
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$notification = [
"to" => '/topics/cbtf',
"data" => [
"message" : "Messaging Topic Message!",
]
]
];
$headers = [
'Authorization: key=AIza...............klQ5SSgJc',
'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($notification));
$result = curl_exec($ch);
curl_close($ch);
return true;
}
You can send notification to any of a topic in firebase. And you can do it from any language it's just a http request but Always you have to maintain the JSON format so that you can catch notification from your android part from
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Timber.d("Data Payload: " + remoteMessage.getData());
}
So You need to send below JSON format
{
"to": "\/topics\/general",
"data": {
"data": {
"title": "Database Notification",
"message": "New Data Added"
}
}
}
So that you can get this data set from remoteMessage.getData()
With particular Topic
<?php
print "testing";
function sendPushnotification($data = array()) {
$apiKey = '';
$fields = array('to' => '/topics/EWAP' , 'notification' => $data);
$headers = array('Authorization: key=' .$apiKey, 'Content-Type: application/json', 'priority' => 10);
$url = 'https://fcm.googleapis.com/fcm/send';
// var_dump($fields);
$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);
curl_close($ch);
return json_encode($result, true);
}
$data = array(
'title' => 'Today topic',
'body' => 'done buddy'
);
var_dump(sendPushnotification($data));
?>
With device token.
<?php
print "testing";
function sendPushnotification($to = '',$data = array()) {
$apiKey = '';
$fields = array('to' => $to , 'notification' => $data);
$headers = array('Authorization: key=' .$apiKey, 'Content-Type: application/json');
$url = 'https://fcm.googleapis.com/fcm/send';
// var_dump($fields);
$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);
curl_close($ch);
return json_encode($result, true);
}
$to = "add device here token ";
$data = array(
'title' => 'Today topic',
'body' => 'done buddy'
);
var_dump(sendPushnotification($to, $data));
?>
I want to send the PUSH notification to the Multiple USERS through PHP script. When I run my script it shows the result successful, but on my device I am not getting any Notification.
But when I use the FCM console, I got the Notifications on my Device.
PHP script:
<?php
function send_notification ($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message,
'click_action' => ACTIVITY_CIRCULAR
);
$headers = array(
'Authorization:key = my key',
'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_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$conn = mysqli_connect("connection set-up");
$sql = "Select FirebaseID From Coordinates";
$result = mysqli_query($conn,$sql);
$tokens = array();
//var_dump(result);
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["FirebaseID"];
}
}
var_dump($tokens);
mysqli_close($conn);
$message = array("message" => "Hello World");
$message_status = send_notification($tokens, $message);
echo $message_status;
?>
My result:
{"multicast_id":6386552330832519***,"success":2,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1477******764957%e8a8d907f9fd7ecd"},{"message_id":"0:1477293027764959%e8a8d907f9f***cd"}]}
EDIT : Is there any way to check where the message is failing because it shows the Successful in Result...but it doesn't reach to device
If you user is more than 1k then you have to chunk you array because FCM registaion_ids not allowed more than 1k id at a time :
$value = array_chunk($userList,900);
foreach ($value as $val)
{
$db->sendPushCustomNew("test" . " Posted a Gallery", $createdDate, $val, "1", "Gotcha!", 0, 0, 0);
}
Then You have to configure you're notification send function like bellow :
function sendPushCustomNew($message, $currentDate, $tokens, $notificationType, $title, $latitude, $longitude, $memberID)
{
//error_log("IN_PUSH");
$curl = curl_init();
$fields = array(
'data' => array(
'notificationType' => $notificationType,
'title' => $title,
"message" => "" . $message,
"time" => "" . $currentDate,
'latitude' => $latitude,
'longitude' => $longitude
),
'registration_ids' => $tokens
);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($fields),
CURLOPT_HTTPHEADER => array(
"authorization: ******",
"cache-control: no-cache",
"content-type: application/json",
"postman-token: ***"
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
}
please check that you have saved the device id properly or not ,and also check that you have used the same server key as per project android key ,check your google account
use this php code its works in your case
<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
'message' => 'here is a message. message',
'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://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;
inside your project you are adding registration id that you get when you create a google api console account from there you ll get server key and android key https://console.developers.google.com/apis/library?project=tabzen-1341,see the screenshot and read the google guidl
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;
}
I'm trying to figure out the paypal API, and I have the following code, which should make a call, get an access token, and then make the API call. The first part works(up until the $accesstoken line), and returns the access token properly, but the second part doesn't return anything. The code this is supposed to mimic can be found here: Make Your First Call
$url = "https://api.sandbox.paypal.com/v1/oauth2/token";
$headers = array(
'Accept' => 'application/json',
'Accept-Language' => 'en_US',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, $clientID . ':' . $clientSecret);
$curl = curl_exec($ch);
$x = json_decode($curl, TRUE);
print_r($x);
$accesstoken = $x['access_token'];
$headers2 = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer' . $accesstoken
);
$data = array(
"intent" => "sale",
"redirect_urls" => array(
"return_url" => "http://example.com/your_redirect_url/",
"cancel_url" => "http://example.com/your_cancel_url/"
),
"payer" => array(
"payment_method" => "paypal"
),
"transactions" => array(
"transactions" => array(
"total" => ".99",
"currency" => "USD"
)
)
);
$saleurl = "https://api.sandbox.paypal.com/v1/payments/payment";
$sale = curl_init();
curl_setopt($sale, CURLOPT_URL, $saleurl);
curl_setopt($sale, CURLOPT_VERBOSE, TRUE);
curl_setopt($sale, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($sale, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($sale, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($sale, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($sale, CURLOPT_HTTPHEADER, $headers2);
$finalsale = curl_exec($sale);
$verb = json_decode($finalsale, TRUE);
print_r($verb);
Curl doesn't make complete sense to me, any help would be appreciated.
UPDATE:
I changed the format of the headers to:
$headers2 = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $accesstoken
);
as per one of the answers. Now it is displaying:
[name] => MALFORMED_REQUEST
[message] => Incoming JSON request does not map to API request
[information_link] => https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST
[debug_id] => f53a882702a04
You are not setting your headers correctly ...
$headers = array(
'Accept: application/json',
'Accept-Language: en_US'
);
and
$headers2 = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $accesstoken
);
Is the correct format.
Also note the (space) after Bearer inbetween your $accesstoken
Edit: Update for your JSON ( i think this is right but echo it out and check it against the reference, I might have one to many array()
$data = array(
"intent" => "sale",
"redirect_urls" => array(
"return_url" => "http://example.com/your_redirect_url/",
"cancel_url" => "http://example.com/your_cancel_url/"
),
"payer" => array(
"payment_method" => "paypal"
),
"transactions" => array(array(
"amount" => array(
"total" => ".99",
"currency" => "USD"
)
)
)
);
You need a space here
$headers2 = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $accesstoken // Added a space after Bearer
);
See if it works now
Change
curl_setopt($sale, CURLOPT_POSTFIELDS, json_encode($data));
to
curl_setopt($sale, CURLOPT_POSTFIELDS, $data);
The json encode function breaks it