I'm working in Facebook bot that replies to some comments (so far so good), yet at some point I need to renew the user authentification token (access_token), yet I still can't get it right. This is my webhook so far...yet I can't get the access token. I used 3 methods yet still nothing. How can I get the renew access token or how to get it with logic that I'm using? No FB SDK implemented so I rather would like to know a solution based on this code.
<?php
if(isset($_GET['hub_mode']) && isset($_GET['hub_challenge']) && isset($_GET['hub_verify_token'])){
if($_GET['hub_verify_token'] == '1234567890')echo $_GET['hub_challenge'];
}else{
$feedData = file_get_contents('php://input');
$data = json_decode($feedData);
$code = NULL;
//$code = $_REQUEST["code"]; //I Tried $_REQUEST yet I can't get the code value.
if (isset($_GET['code'])) { //I tried $_GET yet still no luck.
$code = $_GET['code'];
$app_id = 4444444444444444;
$my_url = 'https://example.com/robots/jotabot-comment-replier/fbwebhook.php';
$app_secret = 'ee....8';
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
//KEEP GOING FROM HERE WITH TOKEN.
http_response_code(200);
return;
}
if($data->object == "page"){
$userMsg = $data->entry[0]->changes[0]->value->message;
$commentID = $data->entry[0]->changes[0]->value->comment_id;
$accessToken = "EAAKGo...AZDZD";
$url = 'https://graph.facebook.com/v15.0/me/messages?access_token='.$accessToken;
$reply = "Thanks for your comment";
$btn1 = array("type"=>"postback","title"=>"OPTION 1","payload"=>"BUDGET_10_PAYLOAD");
$btn2 = array("type"=>"postback","title"=>"OPTION 2","payload"=>"BUDGET_20_PAYLOAD");
$data = array("recipient"=>array("comment_id"=>$commentID),"message"=>array("attachment"=>array("type"=>"template","payload"=>array("template_type"=>"button","text"=>$reply,"buttons"=>[$btn1,$btn2]))));
$postdata = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response);
$errorCode = $data->error->code;
// If we had an error code that means that there is an authentification error.
if ($errorCode) {
$my_url = 'https://example.com/robots/jotabot-comment-replier/fbwebhook.php';
$token_url="https://graph.facebook.com/oauth/authorize?client_id=88884888&redirect_uri=".urlencode($my_url);
//If I put this URL with this parameters manually in my browser I successfully got the redirection with the code that I need:
//https://example.com/robots/jotabot-comment-replier/fbwebhook.php?code=AQS...Puw#_=_
//I tried 3 methods, JS (1st is how documentation suggests), file_get_contents and cURL.
//echo("<script> top.location.href='" . $token_url . "'</script>"); //I tried the way the documentation suggests, yet still no luck.
//$response = file_get_contents($token_url);
//$params = null;
//parse_str($response, $params);
//$access_token = $params['access_token']; //There's no $access_token
$url = $token_url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch); //I tried to catch the code after the redirection yet I can't.
curl_close($ch);
}
}
}
http_response_code(200);
You can't renew your User's access_token without going through Facebook Login flow.
That's why for your application it's better to use Page access_token which has no expiration date. You can read here how to obtain one
Related
Google announced that all google plus api were deprecated on 7th march and I'm using google plus api with oauth2 so I'm worried about is my https://www.googleapis.com/plus/v1/people/me is also deprecated if yes than what is the alternative solution of that..
//index.php
<?php
include('constant.php');
include('google-login-api.php');
// include constant.php
// include google-api library
if(isset($_GET['code'])) {
$gapi = new GoogleLoginApi();
// Get the access token
$data = $gapi->GetAccessToken(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_REDIRECT_URL, GOOGLE_CLIENT_SECRET, $_GET['code']);
if(is_array($data) && count($data)>0)
{
// Get user information
$user_info = $gapi->GetUserProfileInfo($data['access_token']);
echo "<pre>";
print_r($user_info);
}
}else{
//html code
?>
<a class="sign-in sign-google" href="<?php echo GOOGLE_API_URL; ?>"><i class="fa fa-google-plus"aria-hidden="true"></i>Sign In with Google</a>
<?php
}
?>
//google-login-api.php
<?php
class GoogleLoginApi
{
public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
$url = 'https://accounts.google.com/o/oauth2/token';
$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to receieve access token');
return $data;
}
public function GetUserProfileInfo($access_token) {
$url = 'https://www.googleapis.com/plus/v1/people/me';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to get user information');
return $data;
}
}
?>
here is my code which i have using and its run perfectly ...but the question is that Is still running after 7th march
A rough replacement for the Google Plus API (or at least the plus.people portion of the API) is the Google People API. It fundamentally does the same thing (returns profile information for users), although there are some changes in how the request is done and how the response is formatted. The biggest difference is that you need to request exactly what fields you want to receive.
In order to get the information for the user, you'd set $url with something more like
$fields = 'names,emailAddresses';
$url = 'https://people.googleapis.com//v1/people/me?personFields='+$fields;
You can see the reference for people.get for the possible values for the personFields parameter and the OAuth scopes that are valid for access.
Change url from,
$url = 'https://www.googleapis.com/plus/v1/people/me';
to,
$url = 'https://www.googleapis.com/oauth2/v3/userinfo';
I had same issue, solved here
I have an email campaign on Marketo to send emails using PHP. on my email template I have a token like, {{my.emailBody:default=Body}} I would like to replace the the token with my custom email content from my PHP code,
This is my code,
$sample = new SendSampleEmail();
$sample->id = 11111;
$sample->emailAddress = "myemail#example.com";
print_r($sample->postData());
class SendSampleEmail{
private $host = "https://AAA-AAA-121.mktorest.com";
private $clientId = "dxxxxxxxxxxxxxxxxxxxxx1";
private $clientSecret = "Sxxxxxxxxxxxxxxxxxxxxxxxxxxxxe";
public $id; //id of to delete
public $emailAddress;//email address to send to
public $textOnly;//boolean option to send text only version
public $leadId;// id of lead to impersonate
public function postData(){
$url = $this->host . "/rest/asset/v1/email/" . $this->id . "/sendSample.json?access_token=" . $this->getToken();
$requestBody = "&emailAddress=" . $this->emailAddress;
if (isset($this->textOnly)){
$requestBody .= "&textOnly=" . $this->textOnly;
}
if (isset($this->leadId)){
$requestBody .= "&leadId=" . $this->leadId;
}
//print_r($requestBody);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_getinfo($ch);
$response = curl_exec($ch);
return $response;
}
private function getToken(){
$ch = curl_init($this->host . "/identity/oauth/token?grant_type=client_credentials&client_id=" . $this->clientId . "&client_secret=" . $this->clientSecret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = json_decode(curl_exec($ch));
curl_close($ch);
$token = $response->access_token;
return $token;
}
}
Using this code I can successfully trigger the emails, but how can I replace the token value {{my.emailBody:default=Body}} ?
I have the same problem which I tried to used Assets Tokens from the REST API: http://developers.marketo.com/rest-api/assets/tokens/
to modify token's values, but it is the only endpoint I cannot make it work. Please let me know if you could make it work.
However, I used the SOAP API to solve for this issue:
You create a Batch Campaign from Marketo inside a Marketo Program that contains the Token you want to modify and the email you want to send using that token.
The SOAP API will schedule the campaign to run (you can set the current time for immediate run), and you can set the value for the tokens:
public function schedule_campaign($program_name,$campaign_name,$token_name,$token_value)
{
$params = new stdClass();
$params->programName = $program_name;
$params->campaignName = $campaign_name;
$dtzObj = new DateTimeZone("America/New_York");
$dtObj = new DateTime('now', $dtzObj);
$params->campaignRunAt = $dtObj->format(DATE_W3C);
$token = new stdClass();
$token->name = "{{my.".$token_name."}}";
$token->value = $token_value;
$params->programTokenList = array("attrib" => $token);
$params = array("paramsScheduleCampaign" => $params);
$soapClient = new SoapClient(MARKETO_SOAP_ENDPOINT ."?WSDL", self::$auth_options);
try
{
$response = $soapClient->__soapCall('scheduleCampaign', $params, self::$auth_options, self::$auth_header);
return true;
}
catch(Exception $ex) {
return false;
}
}
UPDATE:
I've found the way to update/replace tokens using REST API:
public function create_token($folder_id,$name,$content,$folder_type = 'Program')
{
$folder_id = intval($folder_id);
$endpoint = 'rest/asset/v1/folder/'.$folder_id.'/tokens';
$url = $this->url . $endpoint . ".json?access_token=" . self::$token."&folderType=".$folder_type."&name=".$name."&type=". urlencode('rich text')."&value=".urlencode($content);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
Token replacement only works with the Request Campaign and Schedule Campaign APIs, you can't replace my tokens with the send sample email API.
Having this code, which works:
$appsecretProof = hash_hmac('sha256', $shortLivedToken, $secret);
//init curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'facebook-php-3.2');
//get extended user access token
$url = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token' .
'&client_id=' . $appId .
'&client_secret=' . $secret .
'&fb_exchange_token=' . $shortLivedToken .
'&appsecret_proof=' . $appsecretProof;
curl_setopt($ch, CURLOPT_URL, $url);
$curlResult = curl_exec($ch);
$response_params = [];
parse_str($curlResult, $response_params);
$extendedUserToken = $response_params['access_token'];
$appsecretProof = hash_hmac('sha256', $extendedUserToken, $secret);
//get extended page access token
$url = 'https://graph.facebook.com/' . $pageId .
'?fields=access_token' .
'&access_token=' . $extendedUserToken .
'&appsecret_proof=' . $appsecretProof;
curl_setopt($ch, CURLOPT_URL, $url);
$curlResult = curl_exec($ch);
curl_close($ch);
$pageToken = json_decode($curlResult)->access_token;
How to achieve the same using the regular Facebook SDK? Googling didn't really help. Either I find nothing usable or the solutions do not work, throwing errors like "An access token is required to request this resource" or similar stuff. I already tried a lot but nothing really works.
My last approach was:
FacebookSession::setDefaultApplication($appId, $secret);
$shortLivedSession = new FacebookSession($shortLivedToken);
$shortLivedSession->getLongLivedSession();
$request = new FacebookRequest($shortLivedSession, 'GET', '/' . $pageId . '?fields=access_token');
$response = $request->execute();
$result = $response->getGraphObject()->asArray();
$pageToken = $result['access_token'];
$facebookSession = new FacebookSession($pageToken);
This code always returns a short-lived token.
Figured it out and #luschn, there seems to be the same error in the code on your blog.
What helped was to replace these two lines:
$shortLivedSession->getLongLivedSession();
$request = new FacebookRequest($shortLivedSession, 'GET', '/' . $pageId . '?fields=access_token');
with these:
$longLivedSession = $shortLivedSession->getLongLivedSession();
$request = new FacebookRequest($longLivedSession, 'GET', '/' . $pageId . '?fields=access_token');
I am using below code to post the image to user's wall.
postToFB.php
<?php
session_start();
ini_set("display_errors",1);
include_once "facebook.php";
//The value of $img_src was getting null because the page reloads after the authorization.
//So I stored the value of the image source in the session.
//And then stored that value in $img_src
//By Ashish Shah
if($_GET["f"]){
$_SESSION['imgSrc'] = $_GET["f"];
}
$img_src = $_SESSION['imgSrc'];
$app_id = "APP_ID";
$app_secret = "APP_SECRET";
$post_login_url = "REDIRECT_URL";
$code = $_REQUEST["code"];
$location = $_SESSION['backUrl'];
//echo "Image URL: ".$img_src;
//Obtain the access_token with publish_stream permission
if(empty($code)){
$dialog_url= "http://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&scope=publish_actions";
echo("<script>top.location.href='" . $dialog_url
. "'</script>");
}
else {
$token_url="https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
//echo "Response: $response<br>";
parse_str($response, $params);
$access_token = $params['access_token'];
//Posting Image to The Facebook
$api_url = 'https://graph.facebook.com/v2.0/me/photos';
$attachment = array(
'url' => "{$img_src}",
'access_token' => $access_token
);
$api_response = UseCurl($api_url, $attachment);
$post_result = json_decode($api_response, TRUE);
header('Refresh: 5; URL='.$location);
#print_r($post_result);
echo "You have uploaded the image to your facebook account.<br>";
echo "Now you will be redirected to the previous page.";
}
function UseCurl($url, $attachment){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close ($ch);
return $result;
}
?>
And this is working perfectly.
But my problem is there is some limit to uploading.
This code is making an album of my app's name and stores all the uploaded (Posted) images in that album.
Now, I have to delete the images of that album to upload more after some number of images I have uploading. I don't know the exact number of images allowed.
Can any one help me with this so that user have not to delete the images to upload (post) more images using my app?
Thank you,
Update:
With the above question I also want to add some features such as while uploading I want to make user select the sharing options like "Share With Friends" such as in the facebook itself.
Is there any way to add this feature using my original code?
I am working on an app through my developer test account and all I am doing is trying to post a test notification to my user. I am doing this using the facebook requests 2.0 documentation, so my code looks like this:
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $app_id .
"&client_secret=" . $app_secret .
"&grant_type=client_credentials";
$app_access_token = file_get_contents($token_url);
$user_id = $this->user->id;
$apprequest_url ="https://graph.facebook.com/" .
$user_id .
"/apprequests?message='testing notification'" .
"&" .
$app_access_token . "&method=post";
$result = file_get_contents($apprequest_url);
echo "Request id number: " . $result;
When i do this I get an error on the page that says "failed to open stream", however when I copy and paste the url into the address bar I don't get any errors and get returned a request id. Anybody know why this might be happening?
I solved it using curl instead of file_get_contents. file_get_contents used to throw errors for some reason.
the cpde for the curl is:
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_URL, $apprequest_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
curl_close($ch);
I know I'm a litle late, but I hope it helps somebody.
You should set allow_url_fopen to On