Facebook PHP SDK - how to get a long lived page access token - php

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');

Related

Can't get the renew access token in FACEBOOK APP

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

What is the alternative solution of deprecated google plus api?

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

Get email on OAuth Twitter (Php)

I use Php for twitter autorization (OAuth). Can not get user email in response.
define('ACCOUNT_EMAIL','https://api.twitter.com/1.1/account/verify_credentials.json');
$oauth_nonce = md5(uniqid(rand(), true));
$oauth_timestamp = time();
$oauth_token = $response['oauth_token'];
$oauth_token_secret = $response['oauth_token_secret'];
$screen_name = $response['screen_name'];
//create oauth signature
$params = array(
'oauth_consumer_key=' . CONSUMER_KEY . URL_SEPARATOR,
'oauth_nonce=' . $oauth_nonce . URL_SEPARATOR,
'oauth_signature_method=HMAC-SHA1' . URL_SEPARATOR,
'oauth_timestamp=' . $oauth_timestamp . URL_SEPARATOR,
'oauth_token=' . $oauth_token . URL_SEPARATOR,
'oauth_version=1.0' . URL_SEPARATOR,
'screen_name=' . $screen_name,
//'include_email=true'
);
$oauth_base_text = 'GET' . URL_SEPARATOR . urlencode(ACCOUNT_EMAIL) . URL_SEPARATOR . implode('', array_map('urlencode', $params));
$key = CONSUMER_SECRET . '&' . $oauth_token_secret;
$signature = base64_encode(hash_hmac("sha1", $oauth_base_text, $key, true));
// get userinfo
$params = array(
'oauth_consumer_key=' . CONSUMER_KEY,
'oauth_nonce=' . $oauth_nonce,
'oauth_signature=' . urlencode($signature),
'oauth_signature_method=HMAC-SHA1',
'oauth_timestamp=' . $oauth_timestamp,
'oauth_token=' . urlencode($oauth_token),
'oauth_version=1.0',
'screen_name=' . $screen_name,
//'include_email=true'
);
$url = ACCOUNT_EMAIL . '?' . implode(URL_SEPARATOR, $params);
$response = file_get_contents($url);
print_r($response);
When **include_email=true is open - i get nothing.
When include_email=true is block - i get all userinfo (without email).**
In my admin profile I set Request email addresses from users and send info for special permission in twitter support.
Regenerate keys too.
What is problem in it&
Add cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
print_r($result);
1 way
url = https://api.twitter.com/1.1/account/verify_credentials.json?oauth_consumer_key=XXXXXXXX&oauth_nonce=XXXXXX&oauth_signature=XXXXX&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1509963372&oauth_token=XXXXXX&oauth_version=1.0&screen_name=ssds
result = HTTP/1.1 200 OK + all field without email
2 way
url = https://api.twitter.com/1.1/account/verify_credentials.json?oauth_consumer_key=XXXXXXXX&oauth_nonce=XXXXXX&oauth_signature=XXXXX&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1509963372&oauth_token=XXXXXX&oauth_version=1.0&screen_name=ssds&include_email=true
result = HTTP/1.1 401 Authorization Required + {"errors":[{"code":32,"message":"Could not authenticate you."}]}
2 way with email not work.
I solved this problem and get email!
This is view of last url
define('ACCOUNT_EMAIL','https://api.twitter.com/1.1/account/verify_credentials.json');
curl_setopt($curl, CURLOPT_URL, ACCOUNT_EMAIL . '?include_email=true&screen_name='.$screen_name);

How to replace tokens on email campain using REST API in PHP ?

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.

Facebook Requests 2.0 Error #200 All users in param ids must have accepted TOS

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

Categories