Google Drive API 401 when trying to download a file - oauth-2.0

I'm using the google-api-php-client to get the URL for a document on my Google Drive. The URL works correctly when I paste it into my browser and I can download the file.
However, in my PHP app I always get a 401. Here's my code:
private function _get_document_contents($url)
{
// prepare opts
$opts = array(
'http' => array(
'method' => 'GET',
'header' => "Gdata-version: 3.0\r\nAuthorization: Bearer " . $this->_token . "\r\n"
)
);
// get the doc
return file_get_contents($url . '&exportFormat=html&format=html', false, stream_context_create($opts));
}
I've tried changing Bearer to OAuth (that's what OAuth 2.0 playground uses) but both fail.
Any ideas?

Ah the problem seems to be that I'm using the old Google Docs API and should migrate over to the Google Drive SDK. D'oh!

Related

Amazon: is it possible to specify zip code in the URL for Amazon search results?

I have noticed an issue. If I copy Amazon URL with search results and somebody with another IP opens it then the results can be different.
For example:
https://www.amazon.com/s/ref=sr_nr_p_36_0?lo=toys-and-games&rh=n%3A165793011%2Cp_72%3A1248964011&sort=price-desc-rank&low-price=34.99&high-price=34.99
If you open this URL in from Dallas IP you'll get 102 pages with results.
If you open it with Honolulu IP you'll get 101 pages.
If you open it from Russian IP you'll get 93 pages.
Is that possible to specify US ZIP code for shipping right in the url so that it displays same results for every IP address?
Another little issue I have noticed - it displays different page layout for different people. Sometimes it's default blue links, sometimes it has silver buttons. Maybe somebody knows how to lock the design to one layout with url parameters? :)
There is no simple solution, so here is my complicated way.
The idea is: you must send the same request which is get sent when you manually change ZIP in your browser. Then your ZIP code will be remembered for you session.
Here is my solution in PHP using GuzzleHttp Client:
$jar = new \GuzzleHttp\Cookie\CookieJar();
$client = new \GuzzleHttp\Client([
'headers' => [
'accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language' => 'en;q=0.8',
'user-agent' => '', //set some User-Agent or just leave it empty cos it works too
'x-requested-with' => 'XMLHttpRequest'
],
'cookies' => $jar,
]);
try {
$client->post('https://www.amazon.com/gp/delivery/ajax/address-change.html', [
'form_params' => [
'locationType' => 'LOCATION_INPUT',
'zipCode' => '11219', //YOUR ZIP HERE
'storeContext' => 'office-products',
'deviceType' => 'web',
'pageType' => 'Detail',
'actionSource' => 'glow',
]
]);
} catch (RequestException $e) {
echo "Failed to set ZIP";
}
$response = $client->get('...'); //get any other page from Amazon, now it will have proper ZIP
I'm using awesome Guzzle feature - cookies container: http://docs.guzzlephp.org/en/stable/request-options.html#cookies
It can remember and process cookies between requests just like browser would do.
In all further requests you should keep using these cookies and it will return you results for your ZIP.
Of course you can process cookies manually, Guzzle isn't required but makes things simpler.

Auth with Google or Facebook with Socialite / Laravel

I'm using social auth with Socialite / Laravel 5 ( Google & FB)
With Google, I can make it work in local,
I define Redirect URL to :
http://laravel.dev:8000/auth/login/google
in Google Console
But then, when I try to configure server access, I put
https://example.com/auth/login/google
I get:
Error: redirect_uri_mismatch
In my code, I've put a .env variable
APP_BASE = https://example.com
And in config/services.php
I have :
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('URL_BASE').'auth/login/google',
]
Once more, this works great in local...
What's wrong with my code???
I think env('URL_BASE') should be env('APP_URL').

google drive sdk/google drive api ----using PHP web application

I am creating website page using Google drive API which do following stuff:--
provide user set of pdf file which is stored in my Google drive without any type of Login / authentication by any means and file are public.
who visit that page and if he/she want to download that file/pdf then he/she can do so just by clicking on it without any signup and login.
i have no idea how to getting started with it...is it necessary to use OAuth 2...
in simple word i want to use google drive as file hosting site to host my file and reach users through website.
please give me your valuable solution...
thanks
For php look here for a full example and video. You have to download the Google Drive API for the programming language you are using. Then use that API to help you auth and access files. Here is an example from Google developers page using PHP
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
You will want to use the PHP client library located here: https://developers.google.com/api-client-library/php/
You will then want to authenticate against google using auth2.
Then you can make calls to the Drive API https://developers.google.com/drive/v2/reference/ using the PHP client library.

tmhOauth twitter api stopped working with update_with_media call

So, this morning I got the following error:
{"errors": [{"message": "The Twitter REST API v1 will soon stop functioning.
Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.",
"code": 68}]}
Since I was using the tmhOauth twitter api I went to look if there are updates for it, and as it seems there is an issue listed here.
I'm using the api to update the status with media like this:
$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "#{$image}",
'status' => "{$text}"
),
true, // use auth
true // multipart
);
I found notes that I should just change the link to use 1.1 instead of 1 but it's still not working.
My main problem was that I didn't read the docs fully! While the change in the url from 1 to 1.1 was sufficient I missed the point by not looking that the new url for update_with_media,
as explained in the documentation, is https://api.twitter.com/1.1/statuses/update_with_media.json, namely it's api instead of the old upload subdomain.
So, now my api call looks like this and all works again:
$code = $tmhOAuth->request('POST', 'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$image}",
'status' => "{$text}"
),
true, // use auth
true // multipart
);
Hope this helps someone.
Instead of using tmhOauth api, use abraham's twitteroauth api ( updated to version 1.1 ) :
https://github.com/abraham/twitteroauth/tree/master/twitteroauth
and replace your code as follows :
$connection = new TwitterOAuth($twitter_consumer_key, $twitter_consumer_secret, $twAccessToken, $twAccessTokenSecret);
$parameters = array(
'media[]' => "#{$image}",
'status' => "{$text}"
);
$code = $connection->post('statuses/update_with_media', $parameters);

Twitter Streaming API with OAuth?

I've been stuck on this for awhile. Does anyone know how to authenticate the Twitter Streaming API requests using OAuth? As of right now I'm authenticating via Basic Authentication, and I would like to completely switch over to OAuth. Also, I'm using Ruby on Rails if that helps.
Thanks
Connecting to the Twitter Streaming API via OAuth is done much the same as connecting via the REST API. Assuming you've already negotiated an access token, you sign and issue the request using the same signing algorithm as for a REST request. With the Streaming API, it's best to use header-based OAuth rather than query-string based.
Here's an example of a signed OAuth-based request for the sample end point:
GET http://stream.twitter.com/1/statuses/sample.json
Signature Base String example:
GET&http%3A%2F%2Fstream.twitter.com%2Fstatuses%2Fsample.json&oauth_consumer_key%3Dri8JxYK2ddwSV5xIUfNNvQ%26oauth_nonce%3DUJb0f3nHhFQkpkWkJzxnFT65xX1TZeuGjww6Q2XWs4%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1306947138%26oauth_token%3D819797-torCkTs0XK7H2Y2i1ee5iofqkMC4p7aayeEXRTmlw%26oauth_version%3D1.0
Authorization Header after signing:
Authorization: OAuth oauth_consumer_key="ri8JxYK2ddwSV5xIUfNNvQ", oauth_nonce="UJb0f3nHhFQkpkWkJzxnFT65xX1TZeuGjww6Q2XWs4", oauth_signature="bN14zlBIdCZCSl9%2B8UV8dB2VWjI%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1306947138", oauth_token="819797-torCkTs0XK7H2Y2i1ee5iofqkMC4p7aayeEXRTmlw", oauth_version="1.0"
Matt Harris has some sample code in PHP demonstrating connecting to the streaming API via OAuth: https://github.com/themattharris/tmhOAuth/blob/master/examples/streaming.php
After you register your application on http://dev.twitter.com this is how it's done in Perl:
#!/usr/bin/perl
use strict;
use AnyEvent::Twitter::Stream;
if ($ENV{FIREHOSE_SERVER}) {
$AnyEvent::Twitter::Stream::STREAMING_SERVER = $ENV{FIREHOSE_SERVER};
}
my $done = AE::cv;
binmode STDOUT, ":utf8";
my $streamer = AnyEvent::Twitter::Stream->new(
consumer_key => 'KEY',
consumer_secret => 'SECRET',
token => 'TOKEN',
token_secret => 'TOKEN SECRET',
method => "filter",
track => "KEYWORDS TO TRACK",
on_tweet => sub {
# CUSTOM CODE HERE
},
on_error => sub {
my $error = shift;
warn "ERROR: $error";
$done->send;
},
on_eof => sub {
$done->send;
},
);
$done->recv;
Try the OmniAuth gem which supports many external providers https://github.com/intridea/omniauth
You should use this gem : Tweetstream which sits on top of em-twitter

Resources