Android GCM messages sending Not receiving - java

I am new to Android GCM service I am sending the message with PHP i got
as a response
{"multicast_id":5035179847798608085,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1399447523487490%5695579af9fd7ecd"}]}
it look like it dose send it but not receiving in on my android app
here is my PHP code :
$registrationId="APA91bHx1bvBURGF4YSMDWGd5fPb33YtWfwEDspbsT-ejAYR0K_rao7NCSUtki7bP_1BvoCWn8fNpqAIPSjchvcy2JGtdJPvVC85cU9fhFoiE-Cos7PyhUhqIkpXznrD2rNhg9sVlWF2J5c9vSLLHP0LJDq5Q5M29dnUGzaROWcGBqsw3673VKM";
// API access key from Google API's Console
// Message to send
$message = "the test message";
$tickerText = "ticker text message";
$contentTitle = "content title";
$contentText = "content body";
//$registrationId = 'DEVICE_ID';
$apiKey = "AIzaSyBx6hRnATNJGeYqeF4fzZLrNriuV2TRacI";
$response = sendNotification(
$apiKey,
$registrationId,
array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, "contentText" => $contentText)
);
echo $response;
$data = array(
'data'=>$messageData,
'registration_ids' => array($registrationIds)
);
var_dump( $headers);
var_dump ($data);
$ch = curl_init();
$data= json_encode($data);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data );
var_dump ($data);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Need help

Are you on a Wifi network. The firewall must allow 5228 open found on Gcm config
You can use a tool to help the check the connection GCM Server for windows

Related

Using credentials to authenticate users

i am new to this api, what i am going through right now is the following:
i can access a user the first time with no problem using the auth code given on the redirect uri when the user authenticates my app, uber suggests to keep/storage credentials to make requests on behalf of any user in the future, buy i can find no way to instantiate a Credential for the user with the token or refresh token, any advice?
i have already tryed something like
Credential c = new Credential()
.setRefreshToken("MA.CAESEACXatFo4kWUn-v7mUHYbwkiATEoATIBMQ.SF5nzFJ1dnAfBpcleiSy8i_l159Kfx6fIhOCmOOmaxo.blR8m0ly-A1iC330pfMmLZ_EgnANn6NFzb83LOzZ374")
.setExpiresInSeconds(2222222222L);
but the constructor of Credential is asking for an accesMethod which i cant seem to get by any chance.
so here goes my PHP answer,
FIRST THING VERY IMPORTANT: when you register a user, take all that information and store it into a database, so you can use the keys you receive to make requests on behalf that user!
every time you want to make an API request on behalf of a user, you should refresh the bearer token with the refresh token you receive, just like this:
first make a class that will control the functions (some of them will not be used by if you not needed):
class uber
{
private $code = '';
private $access_token = '';
private $uber_uid = '';// this is just the id for the
//specific user that you should store in the database
private $refresh_token = '';
private $expires_in = '';
}
after that add some functions within that class: getters and setters for each of the private variables, like this(this is the example for one variable, make them for the rest aswell):
/**
* #return mixed
*/
public function getAccessToken()
{
return $this->access_token;
}
/**
* #param mixed $access_token
*/
public function setAccessToken($access_token)
{
$this->access_token = $access_token;
}
Now, if for example want to use a webhook(i recommend that you do), meaning the link you set in your uber account for redirect uri, when you receive a receipt for example, in order to get that receipt you have to refresh the bearer token just like this:
function refreshToken($refresh_token)//param is the one you stored in your DB under the name refresh_token
{
$provider = $this->getProvidersCredentialsFromYourDatabaseForTheSpecificUser();
// this should return an array
$client_id = $provider['client_id'];
$client_secret = $provider['client_secret'];
$url = 'https://login.uber.com/oauth/v2/token';
$fields = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'grant_type' => "refresh_token",
'refresh_token' => $refresh_token
);
$fields_string = '';
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$result = curl_exec($ch);
$result = json_decode($result,1);
$this->setAccessToken($result['access_token']);
curl_close($ch);
return $result;
}
now that your token is refreshed and set in your private you could make a function to retrieve the receipt, for example, just like this:
public function getRidesReceipt($receipt_id){
$url = "https://sandbox-api.uber.com/v1.2/requests/$receipt_id/receipt";// this is the test environment
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $this->access_token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$result = curl_exec($ch);
return json_decode($result,1);
}
catching the webhook on the link you set is done like this:
$json = file_get_contents('php://input'); //catch the data when posted
$data = json_decode($json,1); // decode it into an array so you could easily read it
if you want to check if it is a recept_ready post you can do it like this:
if($data['meta']['status'] == 'ready' && $data['event_type'] == 'requests.receipt_ready'){
//add you code of what to happen with that receipt
}
i will show you how to make a test on this code on the uber api.
you will need to make 2 more functions for this(REMEMBER TO REFRESH THE TOKEN BEFORE EVERY REQUEST):
function makeRequest($url, $token){
$fields = array(
'start_latitude' => '39.761492',
'start_longitude' => '-122.423941',
'end_latitude' => '35.775393',
'end_longitude' => '-133.417546',
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '. $token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
//the below used for seeing something
echo '<pre>';
print_r(json_decode($result,1));
echo '</pre>';
// the above is just for you to see something(should print print a ride id or whatever you requested), you can comment or delete it
curl_close($ch);
return json_decode($result,1);
}
you can call it like this:
makeRequest($url = 'https://sandbox-api.uber.com/v1.2/requests', $the_bearer_token_you_just_refreshed);
from the information printed when you make the above request take the code and call this function:
function modifyRideStatus($url, $status, $token){
$fields = array(
'status' => $status,
);
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '. $token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if (!$result)
{
echo 'Modified ride to: '. $status;
}
}
and this one you can call like this
modifyRideStatus($url = 'https://sandbox-api.uber.com/v1.2/sandbox/requests/id_of_the_ride_you_requested_and_is_printed_on_the_screen', 'accepted', $the_bearer_token_you_just_refreshed);
these are the statuses you will use(call the function 4 times in this order i post here):
1)accepted
2)arriving
3)in_progress
4)completed
when you call the function with the completed status UBER will make a POST on your webhook with the status receipt_ready and you will capture it if you use my code above.
I hope this helps!! if you have questions let me know please!

Convert Currency

I have got an App where it's needed to convert a set amount of money at runtime, as the App will be deployed in different countries.
Let's say I have a set price at 100$. Is there a simple way to convert it to another currency (that I get based on the Locale of the device)?
Cheers
I am using google finance calculator as user interact with your app you can fetch converted data by using it in php.
function convertCurrency($amount, $from, $to){
$url = "https://www.google.com/finance/converter?a=$amount&from=$from&to=$to";
$data = file_get_contents($url);
preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
$converted = preg_replace("/[^0-9.]/", "", $converted[1]);
return round($converted, 3);
}
I'm using USD to INR converter.
call this function
echo convertCurrency(1, "USD", "INR");
you can't do that by java code cause currency rates flatuating every time.. you can use this api it will updated automatically when currency rates change---
<?php
$from = $_POST["from"];
$to = $_POST["to"];
$amount = $_POST["amount"];
$rawData = currencyConvert($from,$to,$amount);
$regex = '#\<span class=bld\>(.+?)\<\/span\>#s';
preg_match($regex, $rawData, $converted);
$result = $converted[0];
preg_match('!\d+(?:\.\d+)?!', $result, $result);
echo $result[0];
function currencyConvert($from,$to,$amount){
$url = "http://www.google.com/finance/converter?a=$amount&from=$from&to=$to";
$request = curl_init();
$timeOut = 0;
curl_setopt ($request, CURLOPT_URL, $url);
curl_setopt ($request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($request, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($request, CURLOPT_CONNECTTIMEOUT, $timeOut);
$response = curl_exec($request);
curl_close($request);
return $response;
}
?>

PHP RESTful Unsupported media type error

I think it's giving a better performance than it was before. The new development is that though it has not been inserting but at least it issues an understandable error of "Unsupported Media Type" and not displaying code as it was earlier.
What exactly am I to do to correct this error? I'd thought it is because I did not add a content-type, after adding it it gives the same result. I am still running both servers on localhost.
The web service is created in Netbeans using Java while the calling application is created using PHP running under XAMPP. For an overview on the error report see the attached image.
<?php
if (!empty($_POST['username']) && !empty($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$url = "http://localhost:8080/WMWS/webresources/entity.userregistration";
$data = array('username' => $username, 'password' => $password);
$initializeCurl = curl_init();
curl_setopt($initializeCurl, CURLOPT_HTTPHEADER, array(
'method' => "POST",
'Content-type' => "text/plain"
));
curl_setopt($initializeCurl, CURLOPT_URL, $url);
curl_setopt($initializeCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($initializeCurl, CURLOPT_POST, true);
curl_setopt($initializeCurl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($initializeCurl);
var_dump($response); // string(37) "{"username":"test","password":"test"}"
curl_close($initializeCurl);
}
?>
<body>
<form method = "POST">
<label for = "username">Username</label>
<input type = "text" name = "username" />
<label for = "password">Password</label>
<input type = "password" name = "password" />
<button id = "register" name = "register">Register</button>
</form>
</body>

screen signing document not appear, and event=ttl_expired

Hi, I've tried to sign a document using DocuSign's Embedded Signing feature, but when I send a request, the screen signing document doesn't appear, and it redirects me to a page with a URL parameter of event=ttl_expired.
I know that the ttl (time-to-life) = 5 minutes for URL tokens, can someone please help me?
URL Tokens are only valid for 5 minutes. If you are being re-directed to a screen that has a URL parameter of event=ttl_expired then that means you are trying to access a signing workflow from an expired URL token.
When URL tokens expire you need to generate a new one. Have you seen DocuSign's API Walkthroughs? There's 9 common use-cases of DocuSign's REST API and one of them is for Embedded Signing. Each walkthrough has code showing you how to accomplish that task in 6 different languages (PHP, JavaScript, Java, C#, Objective-C, Python).
See here for the walkhthroughs:
http://iodocs.docusign.com/APIWalkthroughs
For instance, since PHP is easy to run from the command line here is a fully working PHP program to generate a valid URL token for signing, taken from the Embedded Signing API Walkthrough. Just enter your credentials and a valid template Id from your account and this will work for you:
<?php
// Input your info:
$integratorKey = '...';
$email = '...#....com';
$password = '...';
$name = "John Doe";
// copy the templateId of an existing template here
$templateId = "C9D9D181-CE57-.....................";
// construct the authentication header:
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (retrieves baseUrl and accountId)
/////////////////////////////////////////////////////////////////////////////////////////////////
$url = "https://demo.docusign.net/restapi/v2/login_information";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication: $header"));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
$response = json_decode($json_response, true);
$accountId = $response["loginAccounts"][0]["accountId"];
$baseUrl = $response["loginAccounts"][0]["baseUrl"];
curl_close($curl);
//--- display results
echo "accountId = " . $accountId . "\nbaseUrl = " . $baseUrl . "\n";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 2 - Create an envelope with an Embedded recipient (uses the clientUserId property)
/////////////////////////////////////////////////////////////////////////////////////////////////
$data = array("accountId" => $accountId,
"emailSubject" => "Hello World!",
"emailBlurb" => "This comes from PHP",
"templateId" => $templateId,
"templateRoles" => array(
array( "email" => $email, "name" => $name, "roleName" => "Signer1", "clientUserId" => "1001" )),
"status" => "sent");
$data_string = json_encode($data);
$curl = curl_init($baseUrl . "/envelopes" );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
"X-DocuSign-Authentication: $header" )
);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
echo "error calling webservice, status is:" . $status . "\nerror text is --> ";
print_r($json_response); echo "\n";
exit(-1);
}
$response = json_decode($json_response, true);
$envelopeId = $response["envelopeId"];
curl_close($curl);
//--- display results
echo "Envelope created! Envelope ID: " . $envelopeId . "\n";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 3 - Get the Embedded Singing View
/////////////////////////////////////////////////////////////////////////////////////////////////
$data = array("returnUrl" => "http://www.docusign.com/devcenter",
"authenticationMethod" => "None", "email" => $email,
"userName" => $name, clientUserId => "1001"
);
$data_string = json_encode($data);
$curl = curl_init($baseUrl . "/envelopes/$envelopeId/views/recipient" );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
"X-DocuSign-Authentication: $header" )
);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
echo "error calling webservice, status is:" . $status . "\nerror text is --> ";
print_r($json_response); echo "\n";
exit(-1);
}
$response = json_decode($json_response, true);
$url = $response["url"];
//--- display results
echo "Embedded URL is: \n\n" . $url . "\n\nNavigate to this URL to start the embedded signing view of the envelope\n";
?>

Can't send PUSH notifications with GCM

I have some code working fine on my localhost, but when I move it all to my server, it doesn't seem to work.
My server is behind a firewall so I decided to use a PHP script to use GCM. Again, I tested it all on localhost and it works but on my server, nothing gets sent.
Here is my PHP script:
<?php
include('tools.php');
// Replace with real BROWSER API key from Google APIs
$apiKey = "xxxx";
// Replace with real client registration IDs
//$registrationIDs = array($_POST['devices']);
$registrationIDs = $_POST['devices'];
$proxy = 'http://proxy.vmsrv.redbrick.dcu.ie:3128';
// Message to be sent
$message = $_POST['message'];
// 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 ) );
curl_setopt( $ch, CURLOPT_PROXY, $proxy);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
print_as_json($result);
// Report all PHP errors
error_reporting(-1);
?>
The only output I get in my console after my Java program has called the script is:
[java] DB: Result: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given in /var/www/tools.php on line 5[]
Is there anyway I can try get some information back to figure out what the problem is???
Edit
tools.php
<?php
function print_as_json($result) {
$all = array();
while($r = mysql_fetch_assoc($result)) {
$all[] = $r;
}
echo(json_encode($all));
}
?>
Remove the line
print_as_json($result);
And use a simple echo instead.
echo $result;
Or you might want to try to see what kind of object it is:
var_dump($result);
I'm not sure what $result looks like. If it is a json string, you can convert it into an array with:
$array = json_decode($result);

Categories

Resources