HI~everyone!
I have gotten the registration_id for the phone and an auth token from google for my gmail account that is performing a push.
But When I send my auth token and registration id to Ubuntu and try to post it by php , php's curl and only curl to request to C2DM to get a message. And I always get the 401 Unauthorized.
And this is my php code ....
$post_params = array ( "Email" => $MY_GOOGLE_ACC, "Passwd" =>
$MY_GOOGLE_PWD, "accountType"=>"GOOGLE", "source=" . $MY_GOOGLE_SRC, "service=ac2dm" );
$first = true;
$data_msg = "";
foreach ($post_params as $key => $value) {
if ($first)
$first = false;
else
$data_msg .= "&";
$data_msg .= urlencode($key) ."=". urlencode($value);
}
$x = curl_init("https://www.google.com/accounts/ClientLogin");
curl_setopt($x, CURLOPT_HEADER, 1);
curl_setopt($x, CURLOPT_POST, 1);
curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg);
curl_setopt($x, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($x);
curl_close($x);
$response = $data;
$authKey = trim(substr($response, 4+strpos($response, "SID=")));
echo $authKey; $collapse_key = 'something';
$post_params = array ( "registration_id" => $DEVICE_TOKEN, "collapse_key" =>
$collapse_key, "data.payload"=>"cakephp" );
$first = true;
$data_msg = "";
foreach ($post_params as $key => $value) {
if ($first)
$first = false;
else
$data_msg .= "&";
$data_msg .= urlencode($key) ."=". urlencode($value);
}
$size=strlen($data_msg);
$x = curl_init("https://android.apis.google.com/c2dm/send");
curl_setopt($x, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Content-Length:'. $size, 'Authorization: GoogleLogin auth=' . $authKey));
curl_setopt($x, CURLOPT_HEADER, 1);
curl_setopt($x, CURLOPT_POST, 1);
curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg);
curl_setopt($x, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($x);
curl_close($x);
$response = $data;
Am I miss somthing or do something wrong?
AND any help would be much appreciated,thanks!!
It seems you are extracting the SID from the response, not the Auth field.
$authKey = trim(substr($response, 4+strpos($response, "SID=")));
should be
$authKey = trim(substr($response, 5+strpos($response, "Auth=")));
Try printing the whole response, you'll see something like:
SID=DQAAAGgA...7Zg8CTN
LSID=DQAAAGsA...lk8BBbG
Auth=DQAAAGgA...dk3fA5N
It's this last field that you're searching for!
Related
I am sending push notification from laravel which I am using as a backend for my app.
I am not getting the push notification on android Oreo, but on lower versions, I am getting it.
What changes should I have to do for getting the notification in android oreo?
Here is the code of fcm.php
<?php
class Fcm {
//Define SendNotification function
function sendNotification($dataArr) {
$fcmApiKey = 'SERVER_KEY';//App API Key(This is google cloud messaging api key not web api key)
$url = 'https://fcm.googleapis.com/fcm/send';//Google URL
$registrationIds = $dataArr['device_id'];//Fcm Device ids array
$message = $dataArr['message'];//Message which you want to send
$title = $dataArr['title'];
$image=$dataArr['image'];
$news_id=$dataArr['news_id'];
$random=$dataArr['random_id'];
// prepare the bundle
$msg = array('message' => $message,'title' => $title,"image"=>$image,"news_id"=>$news_id,"random_id"=>$random);
$fields = array('registration_ids' => $registrationIds,'data' => $msg);
$headers = array(
'Authorization: key=' . $fcmApiKey,
'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 );
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
$_SESSION['result']=$result;
return $result;
}
}
Here is the code of send.php
<html><head><script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script></head><body>
<?php
include 'config.php';
//echo '<pre>';
$title=$_POST['title'];
$msg=$_POST['msg'];
$news_id=$_POST['news'];
//echo $news_id;
//echo msg;
//echo $image;
$sql="SELECT image FROM `app_news` where id='".$news_id."' ";
$check= mysqli_query($con, $sql);
$resultcheck= mysqli_fetch_array($check,MYSQLI_ASSOC);
$random=rand(0,999);
$image=$resultcheck['image'];
$data=array("title"=>$title,"message"=>$msg,"image"=>$image,"news_id"=>$news_id,"random_id"=>$random,"priority" => 10);
///echo'<pre><h1> Data sent through request:<br>';var_dump($data); echo '</h1><br>';
////////////////////////////////GETTING DEVICE DATA///////////////////////////////////
$sql="SELECT * FROM `devices`";
$checkdevices= mysqli_query($con, $sql);
$DeviceIdsArr= array();
//Prepare device ids array
while($rowData = mysqli_fetch_array($checkdevices,MYSQLI_ASSOC)) {
$DeviceIdsArr[] = $rowData['token'];
}
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////SENDING NOTIFICATION//////////////////////////////////////////
require("fcm.php");
$fcm = new Fcm();//Create Fcm class object
$dataArr = array();
$dataArr['device_id'] = $DeviceIdsArr;//fcm device ids array which is created previously
$dataArr['message'] = $data['message'];//Message which you want to send
$dataArr['image'] = $data['image'];
$dataArr['title'] = $data['title'];
$dataArr['news_id'] = $data['news_id'];
$dataArr['random_id'] = $data['random_id'];
$dataArr[ 'priority'] = $data['priority'];
//Send Notification
$fcm->sendNotification($dataArr);
//var_dump($_SESSION['result']);//
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
$results[]=json_decode($_SESSION['result']);
///////////////showing results//////////////
$multicast_id=$results[0]->multicast_id;
$success=$results[0]->success;
$fail=$results[0]->failure;
$message_id=$results[0]->results[0]->message_id;
///////////////////////////////////////////////////
if($success!=''){?>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript">
swal({
title: "Notification sent",
text: "successfully ",
icon: "success",button: "close"
}).then(function() {
//Redirect the user
window.location.href = "notification.php";
//console.log('The Ok Button was clicked.');
});
</script>
<?php } ?>
I installed the Acre extension as written in the acre documentation.
And added the #AcraHttpSender anatomy indicated the site and the sending method in it.
But when I throw an exception or use the following command ACRA.getErrorReporter().handleException(new Exception("123"));, nothing happens to the server.
Although I have a permission to access the network in the manifest and the Internet is always on.
Why is not sending?
And is there a way to manually send accumulated reports using the service after a certain period of time?
I was wrong, I checked the data in the $_POST array, which produced a negative result and the logs were not written, you should use the input stream reading directly like this file_get_contents('php://input');
The question can be considered closed, thank you all, the ACRA logs helped to see that the data is not written to the server.
I had exactly the same issue. If it helps anyone else out, here is my MyApplication.java:
#AcraCore(
buildConfigClass = BuildConfig.class,
reportFormat = StringFormat.JSON
)
#AcraHttpSender(
uri = "https://example.org/my_acra_script.php",
httpMethod = HttpSender.Method.POST
)
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
// The following line triggers the initialization of ACRA
ACRA.init(this);
}
}
...just change the uri value.
And here is my_acra_script.php:
<?php
$NEW_LINE = "\r\n";
$from = "server#example.org";
$to = "you#example.org";
$subject = "Android Crash Report";
$headers = "From: $from" . $NEW_LINE;
$headers .= 'MIME-Version: 1.0' . $NEW_LINE;
$headers .= 'Content-type: text/html; charset=utf-8' . $NEW_LINE;
$message = "<html>";
$message .= " <head>";
$message .= " <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";
$message .= " <title>$subject</title>";
$message .= " </head>";
$message .= " <body>";
$message .= " <p>";
$post_data = file_get_contents('php://input');
if (empty($post_data)) {
$message .= "No data received.";
}
else {
$error_data = json_decode($post_data, true);
foreach ($error_data as $key => $value) {
$message .= "<br /><b>" . nl2br(htmlspecialchars($key)) . ":</b><br />" . nl2br(htmlspecialchars($value)) . "<br />" . $NEW_LINE;
}
}
$message .= " </p>";
$message .= " </body>";
$message .= "</html>";
$result = mail($to, $subject, $message, $headers);
if ($result === TRUE) {
echo "OK";
}
else {
error_log("ACRA email not sent.");
}
?>
...just change the $from and $to values.
I have device token "apid" from android phone. I get the valid response that notification is send. but i dont receive the notification. can some one please guide me i am using the following code. i am using php for sending notification
$contents = array();
$contents['alert'] = 'test notification for android';
$notification = array();
$notification['android'] = $contents;
$platform = array();
array_push($platform, "android");
$dev['apid'] = 'valid_device_token_from_android' ;
$push = array("audience"=> $dev, "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";
Thanks
I'm trying to send a non-collapse message via Google Cloud Messaging. For some reason a new message always replaces the previous one. I've tried to use different collapse-keys with no effect. Also omitting the collapse key does not work. What could be the problem?
This is an example code:
<?php
$ids[] = '<notification registration id of the test phone>';
sendNotification($ids, "test message 1", "key1");
sendNotification($ids, "test message 2", "key2");
function sendNotification($ids, $message, $collapseKey)
{
$apiKey = '<api key here>';
$url = 'https://android.googleapis.com/gcm/send';
$data['title'] = 'AppName';
$data['message'] = $message;
$post['registration_ids'] = $ids;
$post['data'] = $data;
if ($collapseKey) {
$post['collapse_key'] = $collapseKey;
}
$headers = array(
'Authorization: key=' . $apiKey,
'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;
}
?>
From the GCM collapse key documentation, omitting the collapse-key should prevent replacing the old messages. Unless some of your messages already expired or your devices are not connected.
Also, the NOTIFICATION_ID with notify method call is implemented in your client application, not your service side code. So it should not be mattered if you are using HTTP server. You can refer to this documentation about NOTIFICATION_ID in your client application's broadcast receiver. Also this StackOverflow answer about how to generate unique NOTIFICATION_ID.
I am going to answer my own question.
There are two scenarios:
For instance: you send two messages when your phone is offline (no wifi, no data, turned off)
Background/killed app -
I only get one notification, but actually i get the two data-message
Foreground -
I get the two notification
Please remember not to add "collapse_key" parameter.
Hope this can help anyone else with the same problem.
I am running the Google GCM test code from here and it runs on both emulator and phone, however when I do a send message the notification only works on the emulator and not the phone.
GCMIntentService Notifcation
import android.support.v4.app.NotificationCompat;
...
// issues a notification to inform the user that server has sent a message
private void generateNotification(Context context, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher)
.setTicker(context.getString(R.string.app_name)).setContentText(message);
Intent notificationIntent = new Intent(context, Main.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// add notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(FM_NOTIFICATION_ID, builder.build());
}
PHP Send message and send function
require_once 'push_db_functions.php';
$dbf = new push_db_functions();
$id = '40';
$message = "Test Message";
$response = $dbf->sendMessage($id, $message);
$response = json_decode($response);
print_r($response);
public function sendMessage($id, $message) {
$results = mysql_query("SELECT regid FROM test WHERE id = '$id'");
$processed = mysql_fetch_row($results);
$url = 'https://android.googleapis.com/gcm/send';
$apiKey = "AIzaSyD-xxx";
$fields = array('registration_ids' => $processed, 'data' => array( "message" => $message),);
$headers = array('Authorization: key=' . $apiKey, '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);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// execute post
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Send message response
stdClass Object ( [multicast_id] => 5036849453049739126 [success] => 1 [failure] => 0 [canonical_ids] => 0 [results] => Array ( [0] => stdClass Object ( [message_id] => 0:1353799902066759%04108f12f9fd7ecd ) ) ) success
I have 2 regId records in my database, one for the emulator and one for the phone $id 39 and 40 and change them accordingly to send messages to either device.
Database records
id | regid
39 | APA91bFyMJx4b0ddI........ Emulator
40 | APA91bFhwEhHOClkg........ Phone
The phone is running Gingerbread and the program registers and runs correctly on it except for not displaying the notification upon message receipt.
mDisplay = (TextView) findViewById(R.id.display);
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
Log.d("registrationID", "::" + regId);
if (regId.equals("")) {
// automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
}
Any help would be greatly appreciated.
Thanks
Thank you for everyone that responded to this question.
I have resolved the issue:
On my phone under Accounts & Sync, General sync settings, I found that the Background data sync box was not ticked. When set all works fine.
I should have figured this out before asking the question, my apologies.
However I hope this answer can be of assistance to others.