I am trying to get facebook page contents using graph api in codeigniter. when I use access token in controller with a get function, I get the contents. But when I try to use graph url in view file, It's showing an error -- " Invalid OAuth access token"
In my controller, I tried this--
$response2 = $this->get('/me?fields=id,name,posts{actions,comments,message}',$accessToken);
echo "<pre>";
print_r($response2);
the get function is--
public function get($params, $accessToken){
try {
$response = $this->fb->get($params, $accessToken);
return json_decode($response->getBody());
} catch(Facebook\Exceptions\FacebookResponseException $e) {
return $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
return $e->getMessage();
}
}
Here I got the result .
but If I try to use it another view file--
<?php
foreach ($h->result() as $row) {
if ($row->social_network == 'facebook') {
$token = $row->token;
$id = $row->pid;
print_r($id);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v15.0/$id?fields=posts%7Bmessage%2Ccomments%2Cactions%7D&access_token=$token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
$result = json_decode($result);
print_r($result);
}
}
?>
Here I am getting the access token from database that I previously stored. Here It shows me an error--
Invalid OAuth access token - Cannot parse access token
How do I make It work?
Related
I want to link and view the analytics account linked with Google Adwords.
Procedure used:
Authenticating google account with scopes "Ananlytics and Adwords" with following url
https://www.googleapis.com/auth/adwords
https://www.googleapis.com/auth/analytics
After getting the authentication response creating Google analytics service object.
Google ads link API throwing error "Insufficient Premissions" screenshot attached
Script :
<?php
//function to authenticate google account and create analytics service object
function googleAuth(){
if (!empty($code)) {
$postFields = 'client_id=' . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . '&client_secret=' . Configure::read('GOOGLE_OAUTH_CLIENT_SECRET') . '&code=' . $code . '&grant_type=authorization_code&redirect_uri=' . Configure::read('GOOGLE_OAUTH_REDIRECT_URI');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$Rec_Data = curl_exec($ch);
if (curl_exec($ch) === false) {
return $Rec_Data;
}
$Rec_Data = json_decode($Rec_Data, true);
if (isset($Rec_Data['refresh_token'])) {
try {
$credentials = array('client_id' => Configure::read('GOOGLE_OAUTH_CLIENT_ID'), 'client_secret' => Configure::read('GOOGLE_OAUTH_CLIENT_SECRET'), 'redirect_uris' => array(Configure::read('GOOGLE_OAUTH_REDIRECT_URI')));
$client = new \Google_Client($credentials);
$client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessToken($Rec_Data['access_token']);
// Create an authorized analytics service object.
$analytics = new \Google_Service_Analytics($client);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
die();
}
}
} else {
if (!empty($id)) {
header("Location:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=" . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . "&redirect_uri=" . Configure::read('GOOGLE_OAUTH_REDIRECT_URI') . "&access_type=offline&approval_prompt=force&state=" . $id . "&scope=https://www.googleapis.com/auth/adwords https://www.googleapis.com/auth/analytics");
exit;
}
}
}
//function to fetch linked account list
function adwordsLinkAnalytics($analyticsAuth) {
$this->autoRender = false;
try {
$adWordsLinks = $analyticsAuth->management_webPropertyAdWordsLinks
->listManagementwebPropertyAdWordsLinks('123456', 'UA-123456-1');
} catch (apiServiceException $e) {
print 'There was an Analytics API service error '
. $e->getCode() . ':+' . $e->getMessage();
exit;
} catch (apiException $e) {
print 'There was a general API error '
. $e->getCode() . ':-' . $e->getMessage();
exit;
}
pr($adWordsLinks);
exit;
}
Required result: List of the analytics account linked with adwords account.
You are missing scope to management entities in Google Analytics, please look at this https://developers.google.com/identity/protocols/oauth2/scopes#analytics
Please update your scope with "https://www.googleapis.com/auth/analytics.edit"
My suggested Updates:
function googleAuth(){
if (!empty($code)) {
--------------
---- Your existing script ----
--------------
} else {
if (!empty($id)) {
header("Location:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=" . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . "&redirect_uri=" . Configure::read('GOOGLE_OAUTH_REDIRECT_URI') . "&access_type=offline&approval_prompt=force&state=" . $id . "&scope=https://www.googleapis.com/auth/adwords%20https://www.googleapis.com/auth/analytics%20https://www.googleapis.com/auth/analytics.edit");
exit;
}
}
}
Reference Url: https://developers.google.com/identity/protocols/oauth2/scopes#analytics
I am using cURL and PHP to make a request to a test API to return a list of users but I get the following error:
PHP Notice: Trying to get property 'id' of non-object
Not sure where I am going wrong.
Here is my code
<?php
// I am using the JSONPlaceholder website as a test API
$url = 'https://jsonplaceholder.typicode.com/users';
// Initial a new cURL session
$request = curl_init($url);
// Return request as string
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
// Run cURL / execute http request
$response = curl_exec($request);
// Close the cURL resource
curl_close($request);
if ($response === false) {
print "Could not make successful request\n";
} else {
$response = json_decode($response);
print $response->id . "\n";
print $response->name . "\n";
print $response->username . "\n";
}
?>
you have to loop through the response:
if ($response === false) {
print "Could not make successful request\n";
} else {
$response = json_decode($response);
foreach ($response as $item) {
print $item->id . "\n";
print $item->name . "\n";
print $item->username . "\n";
}
}
I have successfully done oauth1.0 authentication for the get methods provided in the api document
http://api.seatseller.travel/docs/interface.html
But I am getting issue in blockticket url in the above document URL : http://api.seatseller.travel/blockTicket. I need to post the parameters along .I have used Oauth1.0 2Leg library in codeigniter.But its giving me the error as :
ExceptionRequest failed with code 401: Error: OAUTH verification
failed.
Take reference of this url for Oauth library. https://github.com/jesstelford/OAuth-PHP
In codeigniter/application/helpers I have created a helper in that I coded
include_once APPPATH . 'libraries/OAuth/OAuthStore.php';
include_once APPPATH . 'libraries/OAuth/OAuthRequester.php';
function getbusUrlPost($url,$data) {
$key = 'key';
$secret = 'secret';
$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
OAuthStore::instance("2Leg", $options);
$method = "POST";
$params =$data;
//var_dump($params);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester($url, $method,$params);
$result = $request->doRequest(0);
// Sign the request, perform a curl request and return the results,
// throws OAuthException2 exception on an error
// $result is an array of the form: array ('code'=>int,
'headers'=>array(), 'body'=>string)
$result = $request->doRequest();
$response = $result['body'];
if ($response !=
'oauth_token=requestkey&oauth_token_secret=requestsecret')
{
echo $response;
}
else
{
ECHO '------';
}
}
catch(OAuthException2 $e)
{
echo "Exception" . $e->getMessage();
}
}
in controller:
<?php
include_once APPPATH . 'libraries/REST_Controller.php';
class BusBooking extends Rest_Controller {
public function get_bus_blockTicket_post() {
if(isset($_REQUEST['availableTripID']) &&
isset($_REQUEST['seatname'])
&& isset($_REQUEST['fare']) &&
isset($_REQUEST['ladiesSeat'])
&& isset($_REQUEST['name']) && isset($_REQUEST['mobile'])
&& isset($_REQUEST['title'])
&& isset($_REQUEST['email']) && isset($_REQUEST['age']) &&
isset($_REQUEST['gender'])){
$url="http://api.seatseller.travel/blockTicket";
$data=array(
'availableTripID'=>$_REQUEST['availableTripID'],
'seatname'=>$_REQUEST['seatname'],
'fare'=>$_REQUEST['fare'],
'ladiesSeat'=>$_REQUEST['ladiesSeat'],
'name'=>$_REQUEST['name'],
'mobile'=>$_REQUEST['mobile'],
'title'=>$_REQUEST['title'],
'email'=>$_REQUEST['email'],
'age'=>$_REQUEST['age'],
'gender'=>$_REQUEST['gender']
);
$sources= getbusUrlPost($url, $data);
}
}
I have also tried with curl. But getting same error.Check the following code with curl.
function getBusblock($data) {
$url="http://api.seatseller.travel/blockTicket";
$header[]= 'Content-Type: application/x-www-form-urlencoded';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('oauth_consumer_key'=>"key",'oauth_signature_method'=>"HMAC-
SHA1",'oauth_timestamp'=>'1557752217','oauth_nonce'=>'5cd969995be23','oauth_version'=>'1.0','oauth_signature'=>'DsMdvOOUI57VTkx5VQokUmi9rvw%3D&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if(curl_error($ch))
{
echo 'error:' . curl_error($ch);
}
echo "<pre>";
echo json_encode($result);
echo "</pre>";
exit;
}
Please help me.I have tried much but I am getting Oauth verification failed issue.
I am expecting response in json format with all the ticket details .But getting this output :
ExceptionRequest failed with code 401: Error: OAUTH verification failed.
when hitted webservice with postman.
Use
CURLOPT_HTTPHEADER
instead of
CURLOPT_POSTFIELDS
i want to get user's inbox of youtube and send a video messsage. below is the code i am using to retrieve inbox. inbox comes shows that inbox of user XXXX but inbox is empty, no messages comes. while i have four video messages in my inbox.
$developer_key='REPLACE_ME';
$client_id= 'REPLACE_ME';
$client_secret='REPLACE_ME';
// error checking; user might have denied access
if (isset($_GET['error'])) {
if ($_GET['error'] == 'access_denied') {
echo('You have denied access. Click here to retry…');
} else {
echo("An error has occurred: ". $_GET['error']);
}
exit;
}
// Step 1: redirect to google account login if necessary
if(!isset($_GET['code']) || $_GET['code'] === '') {
Header('Location: https://accounts.google.com/o/oauth2/auth?client_id='. $client_id .
'&redirect_uri=http://localhost:8080/Test/sendMessage.php' .
'&scope=https://gdata.youtube.com&response_type=code&access_type=offline',
true, 307);
exit;
}
$authorization_code= $_GET['code'];
// Step 2: use authorization code to get access token
$url = "https://accounts.google.com/o/oauth2/token";
$message_post= 'code='. $authorization_code .
'&client_id='. $client_id .
'&client_secret='. $client_secret .
'&redirect_uri=http://localhost:8080/Test/sendMessage.php' .
'&grant_type=authorization_code';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
echo "<pre>";
echo "<br><br> message_post : ";
print_r($result);
if ($cur_error= curl_error($ch)) {
echo($cur_error);
curl_close($ch);
exit;
}
curl_close($ch);
$jsonArray= json_decode($result, true);
if ($jsonArray === null) {
echo("Could not decode JSON.");
exit;
}
if (isset($jsonArray['error'])) {
echo("An error has occurred: ". $jsonArray['error']);
exit;
}
if (!isset($jsonArray['access_token'])) {
echo("Access token not found.");
exit;
}
//The user's authentication token
$access_token= $jsonArray['access_token'];
$title ='krishna'; //The title of the caption track
$lang = 'en'; //The languageof the caption track
//$transcript = $_REQUEST['transcript']; //The caption file data
$inboxUrl ='https://gdata.youtube.com/feeds/api/users/default/inbox?alt=json&&key=AIzaSyBeh0Aevex7q3iRIY5bV3N9gx0WAkNBMi4&access_token=' . $access_token;
echo $inboxUrl . "<br />";
$homepage = file_get_contents($inboxUrl);
echo "file content : <pre>";
print_r($homepage);
YouTube's video responses feature has been retired as explained in
this announcement. While existing video responses are still available,
YouTube no longer supports the ability to retrieve a list of video
responses for a video, to upload new video responses, or to delete
video responses, though you can delete the video that was used in a
video response. Consequently, these functions are also no longer
supported in the API.
https://developers.google.com/youtube/2.0/developers_guide_protocol_video_responses
Hi i am using a different account for google analytics and is returning an error:
GDataauthErrorAuthorizationInvalid Credentials
Though for my previous account is working fine. it could be because i missed some things in the registration process, could anyone give me a detailed steps for the registration to work for oauth 2.0 using api_key for google analytics v2.4
thank you
//returns session token for multiple calls to API
function get_session_token($onetimetoken) {
$output = call_api($onetimetoken, "https://www.google.com/accounts/AuthSubSessionToken");
if(preg_match("/Token=(.*)/", $output, $matches)) {
$sessionToken = $matches[1];
} else {
echo "Error authenticating with Google.";
exit;
}
return $sessionToken;
}
//gets the data
function call_api($sessionToken,$url){
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if ($_SESSION['authSub']==true){
$curlheader[0] = sprintf("Authorization: AuthSub token=\"%s\"/n", $sessionToken);
} else {
$curlheader[0] = "Authorization: GoogleLogin auth=" . $sessionToken;
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
$requrlvisits = sprintf("https://www.googleapis.com/analytics/v2.4/data?ids=ga:%s&dimensions=ga:date&metrics=ga:visits,ga:pageviews,ga:bounces,ga:timeOnSite&start-date=%s&end-date=%s&sort=ga:date&key=%s",$get_profid[9],$date1,$date2,$api_key);
// echo $requrlvisits;
$visitsxml = call_api($_SESSION['sessionToken'],$requrlvisits);
$visits = parse_data($visitsxml);
print_r($visitsxml);