I am learning Facebook app development and I want my app to post a simple message on the wall of the user.
How do I do it using the graph API?
I am using servlets for the development of app.
Firstly you need to get the access_token of the user (after it makes a login) with 'https://graph.facebook.com/oauth/'.
https://developers.facebook.com/docs/authentication/
Notice that his access_token will be retrieved to your own php or whatelse "&redirect_uri=WWW.YOUR_WEB.PHP" by a $REQUEST['code'] that you'll have to uncode in this way:
$code = $_REQUEST['code'];
$url = "https://graph.facebook.com/oauth/access_token?";
$url .= "client_id=" . $APP_ID;
$url .= "&client_secret=" . $APP_SECRET;
$url .= "&code=" . $code;
$url .= "&redirect_uri=" . $MY_URL;
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $url);
$response = curl_exec($c);
curl_close($c);
$response = explode("&", $response);
foreach($response as $key => $value)
{
$pair = explode("=", $value);
$response[$pair[0]] = $pair[1];
unset($response[$key]);
}
$access_token = $response['access_token'];
$expires = $response['expires'];
Later to post on a wall you need to call an url in this way:
_url = "https://graph.facebook.com/" + user_id + "/feed?message=MSG_STRING"
_url += "&access_token=" + access_token;
_url += "&name=NAME_STRING";
_url += "&link=LINK_URL";
_url += "&description=DESCRIPTION_STRING";
_url += "&method=post";
https://developers.facebook.com/docs/reference/api/post/
You can use the socialauth library to post a message on FB wall.
http://code.google.com/p/socialauth/
How to post a message on friend's wall, Visit a following link:-
http://code.google.com/p/socialauth/issues/detail?id=233.
Related
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!
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;
}
?>
I need to add a code to my sendEmail.php bellow which would rotate evenly between two or more recipient. Right now all goes to one recipent "sendto" myemail#gmail.com. So I want to add more myemail-1#gmail.com, myemail-2#gmail.com and so on. This way each will receive fresh leads.
<?php
ob_flush();
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['phone'] = $_POST['phone_1']."- ".$_POST['phone_2']."- ".$_POST['phone_3'];
$_SESSION['liberation'] = $_POST['liberation'];
$sendto = "myemail#gmail.com";
$email = $_POST['email'];
$username= nl2br($_POST['username']);
$subject = "New lead from my website";
$headers = "From: <form#manysites.com> \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<p><strong>Name:</strong> ".$_POST['username']."</p>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$_POST['email']."</p>\r\n";
$msg .= "<p><strong>Phone No.: </strong> ".$_POST['phone_1']."- ".$_POST['phone_2']."- ".$_POST['phone_3']."</p>\r\n";
$msg .= "<p><strong> conviction date:</strong> ".$_POST['liberation']."</p>\r\n";
$msg .= "</body></html>";
#mail($sendto, $subject, $msg, $headers);
header("Location:continue.php");
?>
You can simply use the comma operator and then send it right away.. like this..
$sendto = 'myemail1#gmail.com,myemail2#gmail.com,myemail3#gmail.com';
mail($sendto, $subject, $msg, $headers);
Alternatively, you can use an implode() too..
$myemails = array('myemail1#gmail.com','myemail2#gmail.com','myemail3#gmail.com');
$sendto = implode(',',$myemails);
mail($sendto, $subject, $msg, $headers);
Sending them separately....
$myemails = array('myemail1#gmail.com','myemail2#gmail.com','myemail3#gmail.com')
foreach($myemails as $email)
{
mail($email, $subject, $msg, $headers);
}
I think the challenge here is that this script runs with no knowledge of what happened on any occasion that it previously ran. So, one option would be to store the information about who received the last lead. This way when the next person fills in your web form, you can retrieve the value of the last recipient and send the current lead to the next recipient in an array of defined recipients (then update the information about who was the last recipient for the next time).
If you don't have access to a database (or file or something else that is a 'permanent' type of storage) to store the value of the last recipient in, you could simply randomize who receives the current lead. The law of averages suggests that over time, the lead distribution should be relatively equal, though in practice this could result in one person getting all of the leads in a given period.
$recipients=array("recipient1#email.com","recipient2#email.com");
$randnum = mt_rand(0,1);
$sendto = $recipients[$randnum];
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";
?>
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);