Site token with codeigniter rest. - php

So I am trying to interact with the https://www.gosquared.com api with documentation at:
https://www.gosquared.com/developer/api/now/v3/aggregateStats/
Now I am using codeigniter with REST and CURL I have the following code:
public function __construct()
{
parent::__construct();
$this->load->library('admin/curl');
$this->load->library('admin/rest');
$this->rest->initialize(array(
'server' => 'https://api.gosquared.com/now/v3',
));
$this->rest->api_key('0000000000000000');
$this->rest->site_token('FFF-000000-F');
}
public function index()
{
$result = $this->rest->get('aggregateStats');
var_dump($result);
}
So, this is interacting with the service like it should, except on top of an api key this service also requires a site_token in order to access my information.
With the code I have now $this->rest->site_token('FFF-000000-F'); I get this specific error when I load the page:
Fatal error: Call to undefined method REST::site_token()
If I remove the line of code causing that error, I get this as a result of var_dump($result); (because the site token is not getting passed!)
object(stdClass)#27 (2) { ["code"]=> int(4000) ["message"]=> string(162) "You must specify a site token. It looks like GSN-1234567-X and can be found in the developer section of your account area https://www.gosquared.com/home/developer" }
So my question is:
How do I pass an extra variable site_token into the rest library in codeigniter without receiving any error?
According to the documentation a valid url for interacting with the api would look something like the following (for what it's worth)
https://api.gosquared.com/now/v3/aggregateStats?api_key=0000000000000000&site_token=FFF-000000-F

By placing the api key and the site_key into an array within the actual request, I was able to make it work.
// Removed these lines of code:
$this->rest->api_key('0000000000000000');
$this->rest->site_token('FFF-000000-F');
// Replaced the $result = $this->rest->get('aggregateStats'); with the following:
$data['result'] = $this->rest->get('aggregateStats', array('api_key' => '0000000000000000','site_token' => 'FFF-000000-F'));
Just a side note, may consider placing the api key and the site token into a config file for easier updating in the future.

Related

Twitter API responds with "Your credentials do not allow access to this resource" while calling statuses/update.json

I'm using Hybridauth 3 in my PHP app to make some periodical tweets on behalf of my account.
The app has all possible permissions. I'm giving it all permissions when it asks for them on the first auth step.
After that Twitter redirects me to the specified callback URL and there I'm getting a pair of access_token and access_token_secret.
But when I'm trying to make a tweet using these tokens - it gives me:
{"errors":[{"code":220,"message":"Your credentials do not allow access to this resource."}]}
Here's how I'm trying to make a tweet:
$config = [
'authentication_parameters' => [
//Location where to redirect users once they authenticate
'callback' => 'https://mysite/twittercallback/',
//Twitter application credentials
'keys' => [
'key' => 'xxx',
'secret' => 'yyy'
],
'authorize' => true
]
];
$adapter = new Hybridauth\Provider\Twitter($config['authentication_parameters']);
//Attempt to authenticate the user
$adapter->setAccessToken(/*tokens I've got from getAccessToken() on /twittercallback/*/);
if(! $adapter->isConnected()) {
// never goes here, so adapter is connected
return null;
}
try{
$response = $adapter->setUserStatus('Hello world!');
}
catch (\Exception $e) {
// here I've got the error
echo $e->getMessage();
return;
}
Tried to recreate tokens and key\secret pairs and passed auth process for the app many times, including entering password for my Twitter account (as suggested in some posts on stackoverflow) but still have this error.
P.S. According to this, Hybridauth has fixed the issue in the recent release.
It looks like you are using application authentication as opposed to user authentication. In order to post a tweet, you must authenticate as a user. Also, make sure your Twitter app has read/write privileges.
After comparing headers of outgoing requests from my server with the ones required by Twitter, I've noticed that Hybris doesn't add very important part of the header: oauth_token. At least it's not doing this in the code for Twitter adapter and for the scenario when you apply access token with setAccessToken(). It's just storing tokens in the inner storage but not initializing corresponding class member called consumerToken in OAuth1 class.
So to initialize the consumer token properly I've overridden the apiRequest method for Twitter class (before it used the defalut parent implementation) and added a small condition, so when consumer token is empty before the request - we need to try to init it.
public function apiRequest($url, $method = 'GET', $parameters = [], $headers = [])
{
if(empty($this->consumerToken)) {
$this->initialize();
}
return parent::apiRequest($url, $method, $parameters, $headers);
}
I'm not sure that I've fixed it the best way, but as long as it's working - that's fine.
For your info setAccessToken was fixed in v3.0.0-beta.2 (see PR https://github.com/hybridauth/hybridauth/pull/880)
I faced the same error when implementing a sample app in clojure and the following resource was a huge help to sort out my confusion about application-only auth vs user authentication: https://developer.twitter.com/en/docs/basics/authentication/overview/oauth

{"status":false,"error":"Unknown method"} error CodeIgniter RESTful API

<?php
include(APPPATH.'/libraries/REST_Controller.php');
class Quiz extends REST_Controller{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
public function user_get()
{
$this->load->model('Quizmodel');
$data = $this->Quizmodel->getAll();
$this->response($data, 200);
}
function restclient()
{
$this->load->library('rest', array(
'server' => 'http://localhost/CodeIg/index.php/quiz/'
));
$userr = $this->rest->get('user','','json');
echo $userr;
}
}
?>
I am able to get JSON output if I type http://localhost/CodeIg/index.php/quiz/user in my browser, however if I type http://localhost/CodeIg/index.php/quiz/restclient it gives this error: {"status":false,"error":"Unknown method"}
I tried changing get to post but still the same error.
I referred this page https://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter--net-8814 to do it.
You pinged me on GitHub, even though I haven't used or even thought about this code in at least 4 years.
https://github.com/chriskacerguis/codeigniter-restserver/blob/d19dc77f03521c7a725a4555407e1e4e7a85f6e1/application/libraries/REST_Controller.php#L680
This is where that error is being triggered. Throw a few breakpoints in there or var_dump()'s until you see what is causing the trouble.
You probably want to get off CodeIgniter though, and use something more actively maintained like SlimPHP or Lumen.
firstly I want as you have loaded rest api and created your controller quiz as an api to call , where you can only create your functions like user_get or restclient_get and access them the same manner you are doing.Just change you function name restclient to restclient_get then it will call instead it is even not running at this moment.

Unable to get access token from instagram

Im using this instagram wrapper package for laravel 5.1. Im trying to connect to instagram thorugh the API then auth a user in using
use Vinkla\Instagram\Facades\Instagram;
public function instagramlogin(Request $request)
{
// Get code parameter.
$code = $request->get('code');
// Request the access token.
$data = Instagram::getOAuthToken($code);
// Set the access token with $data object.
Instagram::setAccessToken($data);
// We're done here - how easy was that, it just works!
Instagram::getUserLikes();
// This example is simple, and there are far more methods available.
}
and then be able to get access to his/her profile data. but I keep getting an error stating
ErrorException in Instagram.php line 526:
Undefined property: stdClass::$access_token
How do I auth a user?
I solved this problem. You basically have to use the cosenary instagram package as this package is a wrapper for that package. So if you run through the documentation on the cosenary package and use facades instead, the functions will work.

Google Oauth for YouTube : Why do I get "Undefined index: oauth_token" ( Jim S.' code )

I got a little problem with the OAuth for Google, I use the Jim Saunder Libraire for CodeIgniter (http://codeigniter.com/wiki/OAuth_for_Google) but when I came to my access_youtube function, which look like that :
public function access_youtube()
{ //STEP 2
// Here is the first call to load the library
$params['key'] = 's390075769.onlinehome.fr';
$params['secret'] = 'iHD72YKzWmbm8VTwncht_E-d';
// We can change the signing algorithm and http method by setting the following in your params array.
$params['algorithm'] = 'HMAC-SHA1';
// $params['method'] = "GET";
// We need to reload the library since we left our site beetween Step 1 & 2.
$this->load->library('google_oauth', $params);
// We are using HMAC signing you need to specify the token_secret you got from the request step as the second parameter of this method. So
$token_secret = $this->session->userdata('token_secret');
$oauth = $this->google_oauth->get_access_token(false, $token_secret);
// The access method will return an array with keys of ‘oauth_token’, and ‘oauth_token_secret’
// These values are your access token and your access token secret. We should store these in our database.
$this->session->set_userdata('oauth_token', $oauth['oauth_token']);
$this->session->set_userdata('oauth_token_secret', $oauth['oauth_token_secret']);
// Now you have an access token and can make google service requests on your users behalf
redirect(site_url());
}
I got several error messages :
Undefined index: oauth_token
Undefined index: oauth_token_secret
which refer to the lines $this->session->set_userdata ...
and, after each error message I get :
Message: Cannot modify header information - headers already sent by (output started at /homepages/7/d390075755/htdocs/system/core/Exceptions.php:170)
Filename: libraries/Session.php
Line Number: 671
which, I think is linked with the previous error message.
so I tried that in the constructor :
class Example extends CI_Controller
{
private $CI;
public function __construct()
{
parent::__construct();
$this->CI =& get_instance();
$this->CI->load->library('session');
$oauth = array();
$oauth['oauth_token_secret']='';
$oauth['oauth_token']='';
}
just before my function but it doesn't do anything .. and I'm affraid I'm gonna loose my session variables stock by google ... isn't it ? Do I get my tokens from google ?
Honestly i am not sure how Session will be managed by PHP code so will be of little help for you.
It seems that this line is the cause
$oauth = $this->google_oauth->get_access_token(false, $token_secret);
you are trying to get access_token from the Google to send request to Google API to get user information who ever authorize your application and i guess Google is not returning what has been expected from them.
this can be due to type mismatch in the request data as what Google Oauth is expecting from you and what actually you are sending
In you case i would have used debugger of my Eclipse to see what exactly is going on but for OAuth i already told you in earlier question
You need to store that token you getting at your first step.
Once your user is back from authenticate them-self you need to get access_token using that request token
Once you have request token you are ready to make final API call and it seems that some how your code is failing to get the data from session

CodeIgniter Twitter API (Elliot Haughin's) capturing any URL get parameters with "oauth_token" in it

Seems a little strange.
I am using CodeIgniter with Elliot Haughin's Twitter library. It's an excellent API by the way.
However, I autoload this library in "autoload.php" in the config folder and I noticed ANY URL that has "oauth_token" URL parameter is captured by this library.
For example, when I type
http://localhost/myapp/index.php/controller?oauth_token=1
Then it throws up an error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: libraries/Tweet.php
Line Number: 205
I went through the library and found that the following constructor calling a method that checks the GET parameters.
class tweetOauth extends tweetConnection {
function __construct()
{
parent::__construct();
..
..
..
$this->_checkLogin();
}
and the method "_checkLogin()" does the following
private function _checkLogin()
{
if ( isset($_GET['oauth_token']) )
{
$this->_setAccessKey($_GET['oauth_token']);
$token = $this->_getAccessToken();
$token = $token->_result;
...
...
What would be the best way to fix this?
Why do you have oauth_token in the querystring if you're not checking for a valid oauth_token?
I'm assuming at some point you want to state that a oauth_token has been set and you're just using oauth_token=1 as the parameter?
The library is set to always test against oauth_token, and it's not really a feasible tweak to do it any other way if you're autoloading it. You'd need a whitelist/blacklist of controllers (and maybe methods) it runs on, which pretty much defeats the point of autoloading.
If REALLY need to use oauth_token=1, you could just change it to
if ( isset($_GET['oauth_token']) && $_GET['oauth_token']!==1)
If you were using more than one value for oauth_token (or if your worry is that you can trigger an error by appending oauth_token=X to a URL) you could try and use a regex instead, assuming that all oauth_tokens follow a pattern (32 characters long etc).
Alternatively you could also probably just exit/return false depending on what is returned in $token = $this->_getAccessToken(). Depends what happens elsewhere in the code. Looks like returning false should just work.

Categories