PhoneGap-Android: Push Notification by Urban Airship from my server - php

I am working in a Android PhoneGap app where i need to use push notification by Urban Airship. I integrated(Development+Debug) Urban Airship push notification in my app and send test push from Urban Airship website and receive push to all device successfully.
But i need to send push notification from my windows(IIS installed) server(push text and sent time will vary upon server time). I want to send push text according to my schedule task. Schedule task is complete by PHP code.
So,any clue or idea how can i send push notification from my sever with appropriate schedule?
Thanks in advance.

If you can run PHP on your server, following this documentation should get you there - Urban Airship Simple PHP I have used it and it works great!
You would need to enclose most of it in a function which would then get called by your appropriate schedule.
Edit: added code
<?php
define('APPKEY','XXXXXXXXXXXXXXX'); // Your App Key
define('PUSHSECRET', 'XXXXXXXXXXXXXXX'); // Your Master Secret
define('PUSHURL', 'https://go.urbanairship.com/api/push/');
$contents = array();
$contents['badge'] = "+1";
$contents['alert'] = "PHP script test";
$contents['sound'] = "cat.caf";
$notification = array();
$notification['ios'] = $contents;
$platform = array();
array_push($platform, "ios");
$push = array("audience"=>"all", "notification"=>$notification, "device_types"=>$platform);
$json = json_encode($push);
echo "Payload: " . $json . "\n"; //show the payload
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept: application/vnd.urbanairship+json; version=3;'));
$content = curl_exec($session);
echo "Response: " . $content . "\n";
// Check if any error occured
$response = curl_getinfo($session);
if($response['http_code'] != 202) {
echo "Got negative response from server: " . $response['http_code'] . "\n";
} else {
echo "Wow, it worked!\n";
}
curl_close($session);
?>

Related

ionic - firebase notification using PHP not working

I want to push notification to my Ionic 2 app using firebase. I can push notification directly using firebase console, but I want to send it via php file.
when I send I get a response from PHP as: {"message_id":5718309985299480645}
And there is no notification in the phone.
I have placed this.fcm.subscribeToTopic('all') in the app.component.ts constructor.
I dont know what I am doing wrong..
this.fcm.subscribeToTopic('all') is the only code related to fcm in my app.
MY PHP CODE:
<?php
$data = array('title'=>'FCM Push Notifications');
$target = '/topics/mytopic';
//FCM API end-point
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'my_server_key_from_firebase';
$fields = array();
$fields['data'] = $data;
if(is_array($target)){
$fields['registration_ids'] = $target;
}else{
$fields['to'] = $target;
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
//CURL request to route notification to FCM connection server (provided by Google)
$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('Oops! FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
?>
I EVEN TRIED PUSHBOTS BUT COULD NOT GET NOTFICATIONS ON THE DEVICE WITH PHP
I solved the problem by looking at fcm docs.
I changed the PHP file to:
$data = array('title'=>'Title of the notification', 'body'=>$msg, 'sound'=>'default');
$target = '/topics/notetoall';
$url = 'https://fcm.googleapis.com/fcm/send';
$server_key = 'my_server_api_key_from_firebase';
$fields = array();
$fields['notification'] = $data; // <-- this is what I changed from $fields['body']
if(is_array($target)){
$fields['registration_ids'] = $target;
}else{
$fields['to'] = $target;
}
All plugins must be called after the device ready, specially if they're beeing used in app.components (in some pages, that are not the first one, it can be used inside constructor since the app is already ready and plugins are loaded).
So subscribe to a topic on device ready
this.platform.ready().then(() => {
this.fcm.subscribeToTopic('all')
});
Hope this helps.

Getting Unauthorized Error 401 in Firebase Cloud Messaging in cURL command

I'm going to send Firebase Cloud Messaging and the problem that I'm facing is I get an Unauthorized Error 401.
I got the security key from my Firebase website then set it. The device token is already in database and I read from database with no problem.
This is my code so far:
<?php
function send_notification($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array('registration_ids' => $tokens, 'data' => $message);
$headers = array('Authorization: key=' . "My Firebase key", 'Content-Type: application/json');
echo "work well before init curl";
$ch = curl_init();
echo "init well";
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, $fields);
echo "init finishe well";
$result = curl_exec($ch);
echo "Execute to get result";
if ($result === false) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
echo "function finished well";
return $result;
}
$conn = mysqli_connect("localhost", "root", "mysql_password", "FCM") or die("Error connecting");
$sql = " Select Token From users";
$result = mysqli_query($conn, $sql);
$tokens = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["Token"];
}
}
mysqli_close($conn);
$message = array("message" => " FCM PUSH NOTIFICATION TEST MESSAGE");
$message_status = send_notification($tokens, $message);
echo $message_status;
?>
When using FCM, you must use the Server Key seen in the Cloud Messaging tab of your Firebase Console as the value for Authorization in your requests.
Using the documentation at https://developers.google.com/instance-id/reference/server, I wanted to use https://iid.googleapis.com/iid/info/IID_TOKEN to get information about app instances.
In the code of my app, I used this to get the IDD_TOKEN:
// Get token using example from https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/java/MainActivity.java.
// [START retrieve_current_token]
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
System.out.println("task.getResult().getToken() = "+token);
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(FirstActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
// [END retrieve_current_token]
Then in the Android Studio logs, I found the token (I am changing the value of the token because I do not want to post the real one here):
I/System.out: task.getResult().getToken() = bepGr4F2b0Q:APB91cEAKsN1bGjMm5xsobxBHxuYZLfioTPMEIN90njdiK5C2MnOYF5NcOy6ot6XFanMTBIoKRGcyev5RJuydGWt1XHwsniNZ6h3Pjvn9Fqth-Mqgj_2-YN9pv_nMAugG8blc5boeDyH
This means that the IDD_TOKEN was bepGr4F2b0Q:APB91cEAKsN1bGjMm5xsobxBHxuYZLfioTPMEIN90njdiK5C2MnOYF5NcOy6ot6XFanMTBIoKRGcyev5RJuydGWt1XHwsniNZ6h3Pjvn9Fqth-Mqgj_2-YN9pv_nMAugG8blc5boeDyH. So in my PHP code I used this:
$curlUrl = "https://iid.googleapis.com/iid/info/bepGr4F2b0Q:APB91cEAKsN1bGjMm5xsobxBHxuYZLfioTPMEIN90njdiK5C2MnOYF5NcOy6ot6XFanMTBIoKRGcyev5RJuydGWt1XHwsniNZ6h3Pjvn9Fqth-Mqgj_2-YN9pv_nMAugG8blc5boeDyH?details=true";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:key=[My server key]'));
//getting response from server
$response = curl_exec($ch);
print_r($response);
Where is the [My server key] found? You can find it at https://console.firebase.google.com/. Go to the Cloud Messaging tab, and in the Project credentials section, you will find the Server key:
The result was this:
{"applicationVersion":"50","connectDate":"2019-05-09","attestStatus":"NOT_ROOTED","application":"[My package name]","scope":"*","authorizedEntity":"[My Firebase Sender ID]","rel":{"topics":{"Toronto":{"addDate":"2019-05-09"}}},"appSigner":"[My appSigner]","platform":"ANDROID"}
That is correct. I can tell that those values correspond to my IID_TOKEN for the device that I connected, I can recognize that and everything is correct. I can confirm that I subscribed my device to that topic and everything works correctly! I was able to use https://iid.googleapis.com/iid/info/IID_TOKEN to get information about my app instances corresponding to an Android device that I connected using Firebase.

Urban Airship push: Response: Got negative response from server: 0

I am trying to send push notification to my Android app from my server. But it is throwing error Payload: {"audience":"all","notification":{"android":{"alert":"PHP script test "}},"device_types":["android"]} Response: Got negative response from server: 0.
Below is the source code
<?php
define('APPKEY','**************Mw'); // Your App Key
define('PUSHSECRET','**********Low'); // Your Master Secret
define('PUSHURL', 'https://go.urbanairship.com/api/push/');
$contents = array();
$contents['alert'] = "PHP script test";
$notification = array();
$notification['android'] = $contents;
$platform = array();
array_push($platform, "android");
$push = array("audience"=>"all", "notification"=>$notification, "device_types"=>$platform);
$json = json_encode($push);
echo "Payload: " . $json . "\n"; //show the payload
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept: application/vnd.urbanairship+json; version=3;'));
$content = curl_exec($session);
echo "Response: " . $content . "\n";
// Check if any error occured
$response = curl_getinfo($session);
if($response['http_code'] != 202) {
echo "Got negative response from server: " . $response['http_code'] . "\n";
} else {
echo "Wow, it worked!\n";
}
curl_close($session);
?>
I am trying to run this php script from my browser. Push notification from urban airship server is working properly.
Thanks advance for any kind of help.
<?php
// DEVELOPMENT PUSH DETAILS
define('APPKEY','XXXXXXXXXXXXXXXXXXX');
define('PUSHSECRET', 'XXXXXXXXXXXXXXXXXXX'); // Master Secret
define('PUSHURL', 'https://go.urbanairship.com/api/push/');
/*
// PRODUCTION PUSH DETAILS
define('APPKEY','XXXXXXXXXXXXXXXXXXX');
define('PUSHSECRET', 'XXXXXXXXXXXXXXXXXXX'); // Master Secret
define('PUSHURL', 'https://go.urbanairship.com/api/push/');
*/
$push = array();
$push['aliases'] = $aliases; // Using alias that is set from the javascript after the device has registered to urban airship
$push['aps'] = array("badge"=>"+1", "alert" => $message); // for iphone
$push['android'] = array("alert"=>$message); // for android
$json = json_encode($push);
echo "Payload: " . $json . "\n"; //show the payload
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
$content = curl_exec($session); // $content has all the data that came back from urban airship..check its contents to see if successful or not.
// Check if any error occured
$response = curl_getinfo($session);
if($response['http_code'] != 200) {
$status = $response['http_code'];
echo "Got negative response from server: " . $response['http_code'] . "\n";
} else {
$status = 'ok';
}
curl_close($session);
?>
Here, $aliases is array type. It is list of aliases. $message is notification which you want to push. Assign value properly in this two variable. It will work..
According to the HTTP standards, you should include a space between "Content-Type:" and "application/json". Probably the Google server is not interpreting your content-type correctly making it an incorrect request ( It could even be it is rejected due to the Accept: values on the server side ).
Correct your content-type header and try again

Urban Airship - send PUSH to 1 specific device (device token)

So I want to target one specific device token via Urban Airship, but no matter what I do, all of my devices get the message intended for a specific device token.
Here's my PHP code - any help is as usual greatly appreciated!
define('APPKEY','XXXXXXXXXXXXXX');
define('PUSHSECRET', 'XXXXXXXXXXXXX '); // Master Secret
define('PUSHURL', 'https://go.urbanairship.com/api/push/broadcast/');
$msg = "This is a message intended for my iPad 3";
$devicetokens = array();
$devicetokens[0] = $devicetoken;
$contents = array();
$contents['badge'] = "1";
$contents['alert'] = $msg;
$contents['sound'] = "default";
$push = array("aps" => $contents, "device_tokens" =>$devicetokens);
//var_dump($push);
$json = json_encode($push);
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
$content = curl_exec($session);
//var_dump($content); // just for testing what was sent
// Check if any error occured
$response = curl_getinfo($session);
The URL you're using is for broadcasting. To send notification to specific devices, the url you should use is 'https://go.urbanairship.com/api/push/'
Urban Airship have provided sample PHP code to overcome your issue.
Check it out here -> https://github.com/urbanairship/php-library/blob/master/sample.php

Send message to Urban airship using PHP

I am iphone developer and i am working on application, in which i need to send notification to devices in which my application is installed. I done this with the help of Urban airship, now my requirement is to send message from CMS (PHP code) to urban airship(in which my application is registered) and that message will automatically send to my device as notification send earlier from urban airship. Some one guide me that how can i achieve this, or advise me any healthy way to achieve this target
Urban Airship's API documentation can be found here. They also have an article describing a simple use of the API, and an open-source PHP library.
<?php
define('APPKEY','XXXXXXXXXXXXXXX'); // Your App Key
define('PUSHSECRET', 'XXXXXXXXXXXXXXX'); // Your Master Secret
define('PUSHURL', 'https://go.urbanairship.com/api/push/');
$contents = array();
$contents['badge'] = "+1";
$contents['alert'] = "PHP script test";
$contents['sound'] = "cat.caf";
$notification = array();
$notification['ios'] = $contents;
$platform = array();
array_push($platform, "ios");
$push = array("audience"=>"all", "notification"=>$notification, "device_types"=>$platform);
$json = json_encode($push);
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept: application/vnd.urbanairship+json; version=3;'));
$content = curl_exec($session);
echo $content; // just for testing what was sent
// Check if any error occured
$response = curl_getinfo($session);
if($response['http_code'] != 202) {
echo "Got negative response from server, http code: ".
$response['http_code'] . "\n";
} else {
echo "Wow, it worked!\n";
}
curl_close($session);
?>

Categories