Error in Foursquare API - php

I'm currently working with the foursquare API. I downloaded the files from github right here https://github.com/jmathai/foursquare-async. But, when I put my credentials in like my clientId, my client secret, and my redirectUri, it doesn't quite work; it says that there's a redirect uri mismatch. The beginning of the code in the simpleTest.php file looks like this:
ob_start();
require_once 'EpiCurl.php';
require_once 'EpiFoursquare.php';
$clientId = 'CLIENT_ID';
$clientSecret = 'CLIENT_SECRET';
$code = 'CODE';
$accessToken = 'ACCESS_TOKEN';
$redirectUri = 'http://www.thered-line.com/foursquare/simpleTest.php';
$userId = '4855602';
$fsObj = new EpiFoursquare($clientId, $clientSecret, $accessToken);
$fsObjUnAuth = new EpiFoursquare($clientId, $clientSecret);
How to get my $code and $accessToken... ?

This library is for using Foursquare with oAuth. That means that you get your code and access token from part of the oAuth handshake. Foursquare provided you with the client information - the rest is done in the oauth handshake.
When you changed the URL and the user, but kept the code and access token from the original test, you ended up with a code and token that were invalid - you are using the tokens from a handshake that does not have the same data anymore. If you change the test back to how it was on Github, it should run.
Basically, all you need for this lib is the clientID and the Secret - the rest will be done with PHP function calls from the library.
More info

Related

Oauth generate signature without any package

I have to integrate a web application with an API. The API uses OAuth 1.0 to authorize the requests. I have gone through the documentation at http://oauth.net/core/1.0a/. I have followed all the steps to generate the signature But the server always returns the message "invalid signature".
However, if I put my consumer key, consumer secret, access token and access token secret in POSTMAN. Then the signature that is generated by the POSTMAN is accepted by the server.
That means there is nothing wrong with the server. The problem is in the code that I am using to generate the signature.
Here is the code that I have written after reading the documentation to generate the tokens.
$consumer_key = '__MY_CONSUMER_KEY__';
$secret = '__MY__SECRET_KEY__';
$url = 'http://oauth.example.com/oauth/initiate';
$parameters = 'oauth_callback=oob&oauth_consumer_key='.$consumer_key.'&oauth_nonce='.dechex(time()).'&oauth_signature_method=HMAC-SHA1&oauth_timestamp='.time().'&oauth_version=1.0';
$signature = base64_encode(hash_hmac('sha1', 'GET&'.rawurlencode($url).'&'.rawurlencode($parameters), $secret, true));
$signed_request = $url.'?'.$parameters.'&oauth_signature='.$signature.PHP_EOL;
I know there are some predefined the packages available for this But I want to know what is the actual logic to generate the signature for OAuth 1.0.

Where to get accessToken form coinbase sandbox account..?

I am having account in sandbox.coinbase and I have used oauth2 where I have add new app.
It'll provide me :
clientid = 'xxxxxxxx'
clientsecreateid = 'xxxxxxxxxxxxxxxx'
authredirecturl = 'xxxxxxx'
But when I am configure it using below code
$configuration = Configuration::oauth($accessToken);
$client = Client::create($configuration);
I need $accessToken, I go through the document file but I can't find anywhere so any one have idea where to find or how to get accessToken..?
As the documentation states:
This library does not handle the handshake process, and assumes you
have an access token when it's initialized. You can handle the
handshake process using an OAuth2 client such as league/oauth2-client.
So you have to use the oauth2 client first, configure it with the coinbase server (using clientId, clientSecret and redirectUrl that you have) and pass the authorization process (much like "Login with facebook"). At the end of the oauth2 authorization coinbase will send you both access token and refresh token. They are generated on-the-fly.
Alternatively as I can see you can use the apiKey/apiSecret mode. This is essentially like having login/password.

How to get RSS token for BitBucket by PHP CLI?

I want to get valid link https://bitbucket.org/{username}/rss/feed?token={token} (this is main problem) and then get valid response from this link in CLI.
I know my required parameters, e.g. consumer_key, consumer_secret, request_token_url, authenticate_url, access_token_url.
I tried to use StudioIbizz\OAuth\OAuth1, but is seems to be designed for Browser, not for CLI.
I tried to run:
$this->OAuth = new \StudioIbizz\OAuth\OAuth1($this->consumer_key,$this->consumer_secret);
$requestToken = $this->OAuth->getRequestToken($this->request_token_url,$this->authenticate_url);
$token = $requestToken['oauth_token_secret'];
and paste this $token to my RSS link, but then I see message You must have read access to access the RSS feed. from Bitbucket.
I need Step by Step instructions for serious dummies.
Edit: I tried this:
$accessToken = $this->OAuth->getAccessToken($this->access_token_url,$requestToken['oauth_token_secret'],$requestToken['oauth_token']);
But then I get this:
Fatal error: Uncaught exception 'StudioIbizz\OAuth\OAuthException' with message 'Unexpected HTTP status #400'
I don't see any function related with that on official documentation. Maybe that feature not exists.
For more information, you could use this link:
https://confluence.atlassian.com/bitbucket/use-the-bitbucket-cloud-rest-apis-222724129.html
You could use stevenmaguire's Bitbucket OAuth 2.0 support for the PHP League's OAuth 2.0 Client.
$provider = new Stevenmaguire\OAuth2\Client\Provider\Bitbucket([
'clientId' => '{bitbucket-client-id}',
'clientSecret' => '{bitbucket-client-secret}',
'redirectUri' => 'https://example.com/callback-url'
]);
$token = $_GET['code'];
To get an RSS token for Bitbucket via PHP CLI, you will need to use the OAuth 1.0a protocol to authenticate your request. Here are the steps you can follow:
Install an OAuth library for PHP that can be used in CLI, such as the league/oauth1-client package.
Create a new instance of the OAuth client by passing in your consumer key and consumer secret.
$client = new League\OAuth1\Client\Server\Bitbucket($consumerKey, $consumerSecret);
Get the request token by calling the getTemporaryCredentials method and passing in the callback URL.
$temporaryCredentials = $client->getTemporaryCredentials();
Get the authorization URL by calling the getAuthorizationUrl method and passing in the temporary credentials.
$authorizationUrl = $client->getAuthorizationUrl($temporaryCredentials);
Use this URL to authenticate the request via the browser.
After successful authentication, you will get a verifier code.
Get the access token by calling the getTokenCredentials method and passing in the temporary credentials and the verifier code.
$tokenCredentials = $client->getTokenCredentials($temporaryCredentials, $verifier);
$tokenCredentials = $client->getTokenCredentials($temporaryCredentials, $verifier);
Get the RSS token by calling the getRssToken method and passing in the token credentials
$rssToken = $client->getRssToken($tokenCredentials);
You can use this token to construct your RSS feed link:
https://bitbucket.org/{username}/rss/feed?token={$rssToken}
Note that, this is just a general idea of how to use the OAuth library and it may vary depending on the library you are using. It's also important to check the documentation of that library for more details.

YouTube Data API: authenticate as a resource owner

I have a task to import video details of videos, uploaded on YouTube.
I have an account, that is the video owner. I have setup credentials in the console: https://console.developers.google.com/project/XXXXX/apiui/credential. I have created OAuth Service Account there.
Later in the script I am using the code from documentation (v3 version of the API):
$credentials = new Google_Auth_AssertionCredentials(
$clientEmail,
[
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/youtubepartner',
],
$privateKeyContents
);
$this->client->setAssertionCredentials($credentials);
/** #var Google_Auth_OAuth2 $auth */
$auth = $this->client->getAuth();
if ($auth->isAccessTokenExpired()) {
$auth->refreshTokenWithAssertion();
}
Authentication works ok. I've attached logger to Google Client and I can see Authorization: Bearer XXXXXXX header passed with each request.
But the problem is, that it seems, YouTube does not recognize this authentication as an authentication of an actual resource owner. For example, if I request Video Snippet, it is returned without tags (tags can be seen only by owner on some reason).
If I make the same request from here https://developers.google.com/youtube/v3/docs/videos/list?hl=ru it works flawlessly.
What can be the problem?
The request in logs looks like this:
[2015-06-08 14:50:02] name.DEBUG: OAuth2 authentication [] []
[2015-06-08 14:50:02] name.DEBUG: cURL request {"url":"https://www.googleapis.com/youtube/v3/playlists?part=id%2Csnippet&channelId=XXXXXXXXXXXX&maxResults=50","method":"GET","headers":{"authorization":"Bearer ya29.XXXXX-XXXXXX","accept-encoding":"gzip"},"body":null} []
This differs from what I can see if tracing the request Google Javascript client makes on Documentation page. The domain is different, Javascript client passes more headers etc.
How do I make it work with PHP?
You should add onBehalfofContentOwner parameter to your request to show yourself as the content owner.
You seem to have been using Google Service Account credentails for authentication. The API call needs to be made after authenticating as "Client ID for web application" rather than a service account. After you have created a new set of credentials for web application, authenticate as follows:
$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);//This Uri should match exactly to what you had given in Google Developer Console while generating Client ID/Secret
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}
Hope this resolves your problem.

YouTube API OAuth invalid request

I simply don't really understand how this whole OAuth authentification thing works and I'm pretty much stuck. I'm trying to let a user authentificate his/her YouTube account to my server using the Google PHP Client API.
Here's my current code:
<?php
require_once app_path().'/google-apis/Google_Client.php';
require_once app_path().'/google-apis/contrib/Google_YouTubeService.php';
class SignupController extends BaseController {
public function showSignupForm() {
$client = new Google_Client();
$client->setClientId('CLIENTID');
$client->setClientSecret('CLIENTSECRET');
$client->setAccessType('offline');
$client->setDeveloperKey('DEVKEY');
$youtube = new Google_YoutubeService($client);
$client->authenticate(Input::get('code'));
$token = json_decode($client->getAccessToken());
return View::make('signup')->with('google_token', $token->access_token);
}
public function getYTAccess() {
$client = new Google_Client();
$client->setClientId('CLIENTID');
$client->setClientSecret('CLIENTSECRET');
$client->setAccessType('offline');
$client->setDeveloperKey('DEVKEY');
$client->setRedirectUri('REDIRECT_URI');
$youtube = new Google_YoutubeService($client);
$authUrl = $client->createAuthUrl();
return View::make('connect_youtube')->with('authUrl', $authUrl);;
}
}
?>
This is the code for the SignupController in the Laravel-based application I'm building. The relevant routes are as follows:
Route::get('signup/connect_youtube/return', 'SignupController#showSignupForm');
Route::get('signup', 'SignupController#getYTAccess');
I only get an invalid request error after getting redirected to my application and I know it has something to do with the access token, just don't know what.
Any help would be appreciated.
Thanks
Tobias Timpe
(Secrets omitted, obviously)
To put it simply, there are 2 steps (at least) you have to do:
1. pass the correct parameters to google. The parameters tell you 1. who you are (you need to present your client id and client secret), 2. what you ask for (in your case youtube scope) 3. redirect_uri which is where your user will be redirected back after she accepts your app's request. 4. other options like access_type=offline which specifies that you have a backend server to continue the auth flow.
To check that this step works correctly, you don't always need run the code. Just print out your auth_url that the sdk makes for you. All those parameters i mentioned should be embedded there. Copy-paste the url in the browser, if the parameters are correct, it will take you to Google's consent page. If not, most likely is because the parameters you set in Google Apis setting page are mismatched with your parameters scripted in the auth_url. Examples are mismatched domains, redirect_uris, client_ids, client_secrets. I'm not sure if this is the error that you are receiving.
If your parameters are good, Google will let your user to login and allow youtube scope access for your app ('consent'). It will redirect user's browser back to your specified 'redirect_uri' with the parameter code=. So this will get you to the step 2 your server script has to process.
The value shooted from Google in the parameter ?code is what you need to get access token. So your server route (redirect_uri) needs to extract the code parameter and pass to the google api to exchange for 'credentials'. Note that the auth code can be used only once. The response credentials will contain access_token and refresh_token. These are important for the api calling so you need to persist them in a storage, possibly with google sdk you are using.
Hope that helps.

Categories