I'm implementing push notification in android. I have implemented client side coding in android properly. Its working fine and already created Google API key.
Problem: But when I am sending the push notification from the server(this script is written in php) then I am getting error. The error is like this-
{"multicast_id":8690314483687932029,"success":0,"failure":1,"canonical_ids":0,"results": [{"error":"InvalidRegistration"}]}
And my server side script is like this.
<?php
//Generic php function to send GCM push notification
function sendMessageThroughGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
// Update your Google Cloud Messaging API Key
define("GOOGLE_API_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$headers = array(
`` 'Authorization: key=' . GOOGLE_API_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;
}
?>
<?php
//Post message to GCM when submitted
$pushStatus = "GCM Status Message will appear here";
if(!empty($_GET["push"])) {
$gcmRegID = file_get_contents("GCMRegId.txt");
$pushMessage = $_POST["message"];
if (isset($gcmRegID) && isset($pushMessage)) {
$gcmRegIds = array($gcmRegID);
$message = array("m" => $pushMessage);
$pushStatus = sendMessageThroughGCM($gcmRegIds, $message);
}
}
//Get Reg ID sent from Android App and store it in text file
if(!empty($_GET["shareRegId"])) {
$gcmRegID = $_POST["regId"];
file_put_contents("GCMRegId.txt",$gcmRegID);
echo "Done!";
exit;
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) in PHP</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function(){
$("textarea").val("");
});
function checkTextAreaLen(){
var msgLength = $.trim($("textarea").val()).length;
if(msgLength == 0){
alert("Please enter message before hitting submit button");
return false;
}else{
return true;
}
}
</script>
</head>
<body>
<div id="formdiv">
<h1>Google Cloud Messaging (GCM) in PHP</h1>
<form method="post" action="/gcm/gcm.php/?push=true" onsubmit="return checkTextAreaLen()">
<textarea rows="5" name="message" cols="45" placeholder="Message to send via GCM"> </textarea> <br/>
<input type="submit" value="Send Push Notification through GCM" />
</form>
</div>
<p id="status">
<?php echo $pushStatus; ?>
</p>
</body>
</html>
I am new in android. I'm not able to do find what is the exact problem. Please help me, thanks in advance.
change this in your path
action="/gcm/gcm.php/?push=true"
to
action="test/gcm/gcm.php/?push=true"
here test is the folder on the server and gcm is a sub folder. gcm.php should be put in the subfolder.
Related
So I am new to this so please excuse me if my question is not posted as expected. Any suggestions and advice will be kindly appreciated.
So I have a form with multiple fields that posts to an PHP file that verifies an Invisible Google reCAPTCHA and then proceeds to post to Pardot (third party software that notifies our sales team)
Following this post How to Post Form Data to 3rd Party Server After Google Invisible reCaptcha Success?
I can successfully send the email form field to Pardot but I can not seem to send any other fields and/or replace the email field with another one.
In other words I have two fields name="firstname" and name="email" when I send the email field it posts but if I change "email" to "firstname" in the PHP it does not fire.
Based on what I have read I am relatively sure I will need to create an array on the CURLOPT_POSTFIELDS section of my PHP that currently only sends one value ($pardotPost) but before I attempt to send an array I wanted to test the other form fields to see if works as mentioned above.
Here is my client side markup:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Form</title>
<style>
input:required:invalid, input:focus:invalid {
/* insert your own styles for invalid form input */
-moz-box-shadow: none;
color: red!important;
}
input:required:valid {
/* insert your own styles for valid form input */
color: green!important;
}
</style>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("pardot-form-full-width").submit();
}
</script>
</head>
<body>
<div class="mn-call-form-wrapper">
<form id="pardot-form-full-width"
class="uk-form uk-grid-medium uk-form-horizontal invisible-recaptcha"
action="reCAPTCHA.php"
method="POST"
enctype="multipart/form-data"
uk-grid>
<!-- First Name -->
<div class="uk-width-1-2#s">
<input placeholder="First Name *"
class="mix-contact-form-item uk-input"
type="text"
id="firstname"
name="firstname"
required=”required”/>
</div>
<!-- END - First Name -->
<!-- Email Address -->
<div class="uk-width-1-2#s">
<input placeholder="Email *"
class="mix-contact-form-item uk-input"
type="email"
id="email"
name="email"
required="required"/>
</div>
<!-- END - Email Address -->
<!-- Submit Button -->
<div class="mix-signup-submit-button-wrapper">
<button class="g-recaptcha"
data-sitekey="myGrecaptchaKeyIsHere"
data-callback="onSubmit"> Send <span uk-icon="arrow-right" class="uk-icon"></span>
</button>
</div>
<!-- END - Submit Button -->
</form>
</div>
</body>
</html>
Here is my server side markup (reCAPTCHA.php):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Results</title>
</head>
<body>
<?php
// reCaptcha info
$secret = "mySecretKey";
$remoteip = $_SERVER["REMOTE_ADDR"];
$url = "https://www.google.com/recaptcha/api/siteverify";
// Form info
$firstname = $_POST["firstname"];
$response = $_POST["g-recaptcha-response"];
// Curl Request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteip
));
$curlData = curl_exec($curl);
curl_close($curl);
// Parse data
$recaptcha = json_decode($curlData, true);
if ($recaptcha["success"]) {
echo "Thank you, we will be in contact with you soon.";
$pardotPost ='firstname='. $_POST["firstname"];
$curl_handle = curl_init();
$url = "http://pardot.com/our/url";
curl_setopt ($curl_handle, CURLOPT_URL,$url);
curl_setopt($curl_handle, CURLOPT_POST, true);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl_handle, CURLOPT_POSTFIELDS, $pardotPost);
curl_setopt( $curl_handle, CURLOPT_SSL_VERIFYPEER, false );
$result = curl_exec ($curl_handle);
curl_close ($curl_handle);
}
else {
echo "Oh no, it seems something went wrong.";
}
?>
</body>
</html>
In the PHP sections below if I change the values from firstname to email I can confirm the data is sent and ingested by Pardot
// Does not work
$firstname = $_POST["firstname"];
$pardotPost ='firstname='. $_POST["firstname"];
// Does work
$email = $_POST["email"];
$pardotPost ='email='. $_POST["email"];
So my question is two parts.
One - why does the form submit if the email value is used and secondly how would I go about adding several other form fields and send them to Pardot after successful (invisible) Google reCAPTCHA validation?
Thanks in advance!
Okay so this seems to work:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Results</title>
</head>
<body>
<?php
// reCaptcha info
$secret = "key-goes-here";
$remoteip = $_SERVER["REMOTE_ADDR"];
$url = "https://www.google.com/recaptcha/api/siteverify";
// Form info
$email = $_POST["email"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$phone = $_POST["phone"];
$querytype = $_POST["querytype"];
$message = $_POST["message"];
$termsconditionsfw = $_POST["termsconditionsfw"];
$response = $_POST["g-recaptcha-response"];
// Curl Request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteip
));
$curlData = curl_exec($curl);
curl_close($curl);
// Parse data
$recaptcha = json_decode($curlData, true);
if ($recaptcha["success"]) {
echo "Thank you, we will be in contact with you soon.";
//extract data from the post
//set POST variables
$url = 'http://explore.mixtelematics.com/l/69882/2019-01-15/d3zr3d';
$fields = array(
'email' => urlencode($_POST['email']),
'firstname' => urlencode($_POST['firstname']),
'lastname' => urlencode($_POST['lastname']),
'phone' => urlencode($_POST['phone']),
'querytype' => urlencode($_POST['querytype']),
'message' => urlencode($_POST['message']),
'termsconditionsfw' => urlencode($_POST['termsconditionsfw']),
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//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, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
}
else {
echo "Oh no, it seems something went wrong.";
}
?>
</body>
</html>
When I submit this, it sends the information to Pardot :)
I am trying to create push notification for android using php. But I stuck somewhere.I am using an example from for that. Here is my php code
Web config
<?php
/**
* Database config variables
*/
define("DB_HOST", "localhost");
define("DB_USER", "");
define("DB_PASSWORD", "");
define("DB_DATABASE", "");
/*
* Google API Key
*/
define("GOOGLE_API_KEY", "AIzaSyD_PC6UaeTbnSemX0hpY0eyawlE3EufRcA"); // Place your Google API Key
?>
And my GCM.php File is this
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of GCM
*
* #author Ravi Tamada
*/
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);
curl_setopt( $ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
// 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;
}
}
?>
My html is this
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
</script>
</head>
<body>
<form name="" method="post" action="register.php">
<input type="text" name="name"/>
<input type="text" name="email"/>
<input type="text" name="regId"/>
<input type="submit"/>
</form>
</body>
</html>
This the code which I am using but everytime it show me message that
{"multicast_id":4677806556758130005,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I donot know what I am doing wrong
I am getting confuse with GCM Registration Id which I have to pass. Can anybody tell me what is this and where I find it
I tried my project id and project number for that But I got this error again and again
Any help is appreciated
Thanks
Please pass server key of your gcm account if not generated please generate it and pass it it will works 100%
I have two devices registered with GCM. However, when testing sending a message from the server, it only sends a message to that latest registered device instead of all registered devices.
How can this be altered to send to those device ids:
<?php
//generic php function to send GCM push notification
function sendPushNotificationToGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
// Google Cloud Messaging GCM API Key
define("GOOGLE_API_KEY", "(API KEY)"); // My API Key form Google console
$headers = array(
'Authorization: key=' . GOOGLE_API_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;
}
?>
<?php
//this block is to post message to GCM on-click
$pushStatus = "";
if(!empty($_GET["push"])) {
$gcmRegID = file_get_contents("GCMRegId.txt");
$pushMessage = $_POST["message"];
if (isset($gcmRegID) && isset($pushMessage)) {
$gcmRegIds = array($gcmRegID);
$message = array("message" => $pushMessage);
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
}
}
//this block is to receive the GCM regId from external (mobile apps)
if(!empty($_GET["shareRegId"])) {
$gcmRegID = $_POST["regId"];
file_put_contents("GCMRegId.txt",$gcmRegID);
echo "Ok!";
exit;
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in PHP</h1>
<form method="post" action="gcm.php/?push=1">
<div>
<textarea rows="2" name="message" cols="23" placeholder="Message to transmit via GCM"></textarea>
</div>
<div><input type="submit" value="Send Push Notification via GCM" /></div>
</form>
<p><h3><?php echo $pushStatus; ?></h3></p>
</body>
</html>
Check if the new deviceId being stored is not clearing the original contents. I.e. the file operation while adding a new device id Should be of append mode. This might be causing the problem of sending only to the latest device.
I'm trying to send a request to gcm using php
I find this post
GCM with PHP (Google Cloud Messaging)
my code:
public function gcmSend($registrationIdsArray, $messageData) {
// Replace with real BROWSER API key from Google APIs
$apiKey = "my key";
// Replace with real client registration IDs
$registrationIDs = $registrationIdsArray;
// Message to be sent
$message = $messageData;
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'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
$result = curl_exec($ch);
// Close connection
curl_close($ch);
return $result;
}
And it always return :
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
for the api key I try both server key and browser key
for the server key I set the result of
$_SERVER['SERVER_ADDR'];
and for the browser key if my request is http://www.api.mysite.com/test I set
*.mysite.com/*
There is maybe an activation time for the key ?
my server is a mutualised server the ip can be blacklisted ?
Thanks
I'm working on a script for post a message on a visitors wall. The visitor can enter there own message in a form en then send it to facebook.
index.php:
<form name="form" method="post" action="wall.php">
<textarea name="t_update" cols="50" rows="5" id="t_update" >message</textarea><br>
<input type="submit" name="Submit" value="Post To Your facebook Account!">
</form>
This sends "t_update" to "wall.php". The wall.php script is working fine I tested it with static text. but when I try to insert the "t_update" text into the var $APP_MSG it's empty when send to facebook. This is the complete wall.php script.
wall.php:
<?php
/** FB APP DATA **/
$FB_APPID = "Facebook app id";
$FB_SECRET = "Facebook secret code";
/** MSG DATA **/
$APP_MSG = ($_POST['t_update']); // post message
$APP_MSG_LINK_TITLE = "Title";
$APP_MSG_LINK = "www.domain.com";
global $ch;
$code = $_REQUEST["code"];
$error = $_REQUEST["error"];
$returnurl = "http://".$_SERVER["HTTP_HOST"].$_SERVER["SCRIPT_NAME"];
function facebook_curl_request($url,$params=array(),$post = false){
global $ch;
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11');
curl_setopt ($ch, CURLOPT_HEADER, false);
if($post == true){
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
$response = curl_exec ($ch);
$temp = json_decode($response,1);
if(isset($temp["error"]) && is_array($temp["error"])){
echo $temp["error"]["type"]."<br>";
echo $temp["error"]["message"]."<br>";
echo "--------------------------------------------";
curl_close ($ch);
exit;
}
return $response;
}
if(empty($code)) {
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $FB_APPID . "&redirect_uri=" . urlencode($returnurl) . "&scope=publish_stream,email";
header("Location: $dialog_url");
}
if(!empty($error)){
echo $_REQUEST["error"]."<br>".$_REQUEST["error_reason"]."<br>".$_REQUEST["error_description"];
}else{
if(!empty($code)){
/** CREATE TOKEN **/
$ch = curl_init();
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $FB_APPID . "&redirect_uri=" . $returnurl
. "&client_secret=" . $FB_SECRET . "&code=" . $code;
$token = facebook_curl_request($token_url);
$tarr = explode("&",$token);
list($token_name,$token) = explode("=",$tarr[0]);
/**GET USER INFO**/
$graph_url = "https://graph.facebook.com/me?".$token_name."=".$token;
$user = json_decode(facebook_curl_request($graph_url),1);
$userid = $user["id"];
/* POST TO WALL **/
$graph_url = "https://graph.facebook.com/".$userid."/feed";
$params = array(
$token_name => $token,
"message" => $APP_MSG,
'name' => $APP_MSG_LINK_TITLE,
'link' => $APP_MSG_LINK
);
$response = facebook_curl_request( $graph_url, $params, true);
list($userid,$postid) = explode("_",$response);
echo "<html><head></head><body>Bedankt voor het posten op facebook!</body></html>";
curl_close ($ch);
}
}
?>
I've tried everything can anybody point me in the right direction???
I did test the code and can confirm that it's not working. The reason its not is because when you first hit wall.php, you get redirected to Facebook to authenticate, it then redirects back to your application script "wall.php" with a GET - so you lose your POST variables on the redirect. That's why it ends up empty. Your other variables are still there because it's hard coded and will get called regardless when you run the script. Hope that makes sense.
I've just started working on an application and have found using the Facebook PHP SDK alot easier to work with. Code is much cleaner as well. The Dev area has a sample PHP file you can work with that shows you how to authenticate as well.
Example below:
<?php
require_once 'facebook-php-sdk/src/facebook.php';
$APP_MSG = ($_POST['t_update']);
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'SECRET'
));
$wallArgs = array('message' => $APP_MSG);
try {
$facebook->api('me/feed', 'post', $wallArgs);
}
catch(Exception $e) {
print "<pre>";
print_r($e);
print "</pre>";
}
?>
You can also do this in HTML and JavaScript without requesting the users permission. First, initialize the Facebook API in your HTML page. Put this at the BOTTOM of the page, before the closing body tag.
<div id="fb-root"></div>
<script src="https://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '[your_app_id_goes_here];',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
Don't forget to replace [your_app_id_goes_here] with your Facebook App ID. Next, create a JS function that will post on the users wall. Put this in the head of the page.
<script>
// A function to post on the users wall
function wallPost() {
FB.ui(
{
method: 'feed',
name: 'Go find something!',
link: 'http://www.google.com',
picture: 'http://www.google.com/images/logos/ps_logo2.png',
caption: 'Google',
description: 'This was posted from a test app I created.',
message: ''
},
function(response) {
if (response && response.post_id) {
document.getElementById('message').innerHTML = 'Thanks for sharing!';
} else {
document.getElementById('message').innerHTML = 'Hey, you didn\'t share!';
}
}
);
}
</script>
Finally, use the function you just created in a link of some sort.
<p id="message">
Share Me!
</p>
This example is from my book Social App Development by Joel Dare. Get it at social.joeldare.com.