I'm trying the following thing for quite a while now and am heavily struggling...
On a website, I first want to authenticate a user with his Google Account using OAuth. Therefore, I'm using this library. In order to get it working, I used $f3->set('AUTOLOAD','vendor/ikkez/f3-opauth/lib/opauth/'); to load the PHP files and then used the following code to create the routes and make the authentication possible:
$f3 = \Base::instance();
// load opauth config (allow token resolve)
$f3->config('vendor/ikkez/f3-opauth/lib/opauth/opauth.ini', TRUE);
// init with config
$opauth = OpauthBridge::instance($f3->opauth);
// define login handler
$opauth->onSuccess(function($data){
header('Content-Type: text');
//$data['credentials']['token'];
});
// define error handler
$opauth->onAbort(function($data){
header('Content-Type: text');
echo 'Auth request was canceled.'."\n";
print_r($data);
});
So far so good, thats all working fine, once permission is granted from Google I get the correct callback, also including the login token.
Now the next step is, that after user gave permission for that (by authenticating), I want to check, if the user subscribed to a specific channel on Youtube (and afterwards saving that information to my DB, printing it at the first step would be enough though).
Now I did my homework for multiple hours in trying to figuring out how it works...
What I (in general found) is that the following curl request should give me the desired result:
curl \
'https://youtube.googleapis.com/youtube/v3/subscriptions?part=snippet%2CcontentDetails&forChannelId=UC_x5XG1OV2P6uZZ5FSM9Ttw&mine=true&key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--compressed
I then tried to sent this curl request with PHP, substituting the API KEY with my Google API Key and "YOUR_ACCESS_TOKEN" with the token I got from OAUTH.... However, it's throwing an error, saying "request had insufficient authentication scopes"... That seems to be because when checking the PHP example from Google, I have to provide the Scopes I'm using - in my case https://www.googleapis.com/auth/youtube.readonly.
The PHP code provided by Google is the following:
<?php
/**
* Sample PHP code for youtube.subscriptions.list
* See instructions for running these code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#php
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
'https://www.googleapis.com/auth/youtube.readonly',
]);
// TODO: For this request to work, you must replace
// "YOUR_CLIENT_SECRET_FILE.json" with a pointer to your
// client_secret.json file. For more information, see
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys
$client->setAuthConfig('YOUR_CLIENT_SECRET_FILE.json');
$client->setAccessType('offline');
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open this link in your browser:\n%s\n", $authUrl);
print('Enter verification code: ');
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
$queryParams = [
'forChannelId' => 'UC_x5XG1OV2P6uZZ5FSM9Ttw',
'mine' => true
];
$response = $service->subscriptions->listSubscriptions('snippet,contentDetails', $queryParams);
print_r($response);
This let's me run into a new issue... Trying to use this code, I'm getting the error, that Google_Client is not known as class... I then went ahead and installed Google Client with Composer and tried to use vendor/autoload.php in order to use the class.... However, when including the autoload.php, I get the error Fatal error: Cannot declare class Prefab, because the name is already in use... This seems to be the case, because the f3-opauth declares this Prefab class already and then the google apiclient tries to declare it again... However, I didn't manage to to include google apiclient without the autoload...
You see, I really tried a lot and I've been working on this for about 5-6 hours today, only getting that one API request to work and I don't know what else to try...
Any hint on how to get it working would be appreciated - if there's any hint on doing it a completely other way, I'd be willing to change it as well, as the project itself just started.
Summarizing, what I'm trying to do is the following:
-> User can log in on Website with his Youtube/Google Account
-> When authenticating, its checked, if the User is a Subscriber of a specific channel. Next step would be to also check, if he is a channel member of this speicific channel. Both information would need to be saved to database
-> after that, user can always log in into his account with Google again and in the database, you can find the information if the user is subscriber and/or channel member of this channel..
Thanks in advance!
I'm not sure if this will help with your exact use case, but I've worked with Google APIs in the past with Fat-Free. I couldn't get it to work right off the bat, so I installed and got it working with the Google Client/API/SDK. Once I got that working, then I worked backwards to see if I could make it work with Fat-Free. One of the things that I noticed I was running into was missing fields in the Oauth request. access_type was one that got me as well as approval_prompt. I know that you said you've gotten your access token thus far, so it may not apply, but it could for future requests. Here's some example code I've got working to generate an oauth URL for Google Sign in, and then to process the request and make the call to the userinfo portion.
<?php
class App_Auth {
public static function generateOauthUrl() {
$fw = Base::instance();
$Oauth = new \Web\OAuth2();
$Oauth->set('client_id', $fw->get('google.client_id'));
$Oauth->set('scope', 'profile email');
$Oauth->set('response_type', 'code');
$Oauth->set('access_type', 'online');
$Oauth->set('approval_prompt', 'auto');
$Oauth->set('redirect_uri', $fw->SCHEME.'://' . $_SERVER['HTTP_HOST'] . $fw->BASE.'/oauthRedirect');
return $Oauth->uri('https://accounts.google.com/o/oauth2/auth', true);
}
public static function processAuthCodeAndGetToken($auth_code) {
$fw = Base::instance();
$Oauth = new \Web\OAuth2();
$Oauth->set('client_id', $fw->get('google.client_id'));
$Oauth->set('client_secret', $fw->get('google.client_secret'));
$Oauth->set('scope', 'profile email');
$Oauth->set('access_type', 'online');
$Oauth->set('grant_type', 'authorization_code');
$Oauth->set('code', $auth_code);
$Oauth->set('approval_prompt', 'auto');
$Oauth->set('redirect_uri', $fw->SCHEME.'://' . $_SERVER['HTTP_HOST'] . $fw->BASE.'/oauthRedirect');
return $Oauth->request('https://oauth2.googleapis.com/token', 'POST');
}
public static function getOauthUserInfo($access_token) {
$Oauth_User_Info = new \Web\OAuth2();
return $Oauth_User_Info->request('https://www.googleapis.com/oauth2/v2/userinfo', 'GET', $access_token);
}
One other error that has bitten me in the backside was we would get our access token from Google and then store it in the database for subsequent requests. We would get that scopes error you mentioned request had insufficient authentication scopes. We eventually figured out that the access_token was longer than our database field (VARCHAR(32) if I remember right) so we needed to make our database field longer so it would store the whole thing.
Hopefully one of those triggers something for you to figure out your issue.
Related
I am currently new to using php and Laravel and working with an API however I have been following the Spotify PHP tutorial https://github.com/jwilsson/spotify-web-api-php.
I've also put in bold some of my questions that I wanted to ask , hopefully someone can help.
I have followed all steps but need help just to get it working.
Put the following code in its own file, lets call it auth.php. Replace CLIENT_ID and CLIENT_SECRET with the values given to you by Spotify.
(Where abouts should I save this file?)
The REDIRECT_URI is the one you entered when creating the Spotify app, make sure it's an exact match.
(I used my localhost:8888/callback/ not sure if that is correct?) Obviously I haven't put me details in here on this website as for security reasons.
<?php
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ ID',
'CLIENT_SECRET',
'REDIRECT_URL'
);
$options = [
'scope' => [
'playlist-read-private',
'user-read-private',
],
];
header('Location: ' . $session->getAuthorizeUrl($options));
die();
?>
When the user has approved your app, Spotify will redirect the user together with a code to the specifed redirect URI. You'll need to use this code to request a access token from Spotify.
put this code in a new file called callback.php:
Do replace client id and secret with my detail? also how do I save the access token?
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ID',
'CLIENT_SECRET',
'REDIRECT_URI'
);
// Request a access token using the code from Spotify
$session->requestAccessToken($_GET['code']);
$accessToken = $session->getAccessToken();
$refreshToken = $session->getRefreshToken();
// Store the access and refresh tokens somewhere. In a database for example.
// Send the user along and fetch some data!
header('Location: app.php');
die();
In a third file, app.php, tell the API wrapper which access token to use, and then make some API calls!
(Where do i also save this file and how do I make these calls in my Laravel Controllers?)
require 'vendor/autoload.php';
$api = new SpotifyWebAPI\SpotifyWebAPI();
// Fetch the saved access token from somewhere. A database for example.
$api->setAccessToken($accessToken);
// It's now possible to request data about the currently authenticated user
print_r(
$api->me()
);
// Getting Spotify catalog data is of course also possible
print_r(
$api->getTrack('7EjyzZcbLxW7PaaLua9Ksb')
);
(Where abouts should I save this file?)
You can save this file in differents places in laravel, for testing you could write it in a controller (not the best but you can).
Do replace client id and secret with my detail?
Yes of course !
also how do I save the access token?
You can save in a database or in a session or where you want. If you store it in a session you will have to make a new request to get a new Access token if the user logged out of your application. In a database you can reuse it.
Many access token are only available for a specific duration. The spotify doc should speak of it.
(Where do i also save this file and how do I make these calls in my Laravel Controllers?)
For testing you can do this in your controller, but it's a good idea to have a service layer where you put the business logic of your application.
Do not copy require 'vendor/autoload.php'; in your file laravel handle the composer autoload already.
Updated:
My project is to be able to provide a web based application which allows the visitor to upload/download/delete files using GoogleDrive. The project requires it to be server based, which does not require credentials from the user to be able to perform these functions.
In a nutshell, the web application stores the files on a single dedicated google drive account, instead of storing the files on the server.
I researched Google's developer site, and was directed to using the example below as a starting point, to configure the PHP application to use the Drive Account I set up.
I followed the instructions per Google's page:
https://code.google.com/p/google-api-php-client/wiki/OAuth2#Service_Accounts
When I execute this script, I am receiving the following 500 error:
PHP Catchable fatal error: Argument 3 passed to
Google_HostedmodelsServiceResource::predict() must be an instance of
Google_Input, none given, called in
/data/sites/scott/htdocs/dfs_development/drive/serviceAccount.php on
line 62 and defined in
/data/sites/scott/htdocs/dfs_development/apis/google-api-php-client/src/contrib/Google_PredictionService.php
on line 36
What am I doing wrong here? I am uncertain what $project variable should hold, and it seems the predict() function needs 3 args, however I am at a loss to know what it should be.
Here is my code, which I obtained from the URL above. Thank you in advance for your response.
require_once '../apis/google-api-php-client/src/Google_Client.php';
require_once '../apis/google-api-php-client/src/contrib/Google_PredictionService.php';
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = '##########.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = '#########developer.gserviceaccount.com';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = 'pathto/secretlystored/######-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("My Google Drive");
// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/prediction'),
$key)
);
$client->setClientId(CLIENT_ID);
$service = new Google_PredictionService($client);
// Prediction logic:
$id = 'dfslocalhost';
$predictionData = new Google_InputInput();
$predictionData->setCsvInstance(array('Je suis fatigue'));
$input = new Google_Input();
$input->setInput($predictionData);
$result = $service->hostedmodels->predict($id, $input); ## 500 ERROR occurs here..
print '<h2>Prediction Result:</h2><pre>' . print_r($result, true) . '</pre>';
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
thats because Google_PredictionService API has not actived in your google API console dev.
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.
I've successfully made my way through the LinkedIn OAuth process (using the REST API - OAuth 1.0a). However I'm having trouble with my first API call after the callback. I set the UserToken, UserTokenSecret and UserVerfier in the library I am writing, and this call this function to get my profile information:
public function getUserProfile()
{
$consumer = new OAuthConsumer($this->consumer_key, $this->consumer_secret, NULL);
$auth_token = new OAuthConsumer($this->getUserToken(), $this->getUserTokenSecret());
$access_token_req = new OAuthRequest("GET", $this->access_token_endpoint);
$params['oauth_verifier'] = $this->getUserVerifier();
$access_token_req = $access_token_req->from_consumer_and_token($this->consumer,
$auth_token, "GET", $this->access_token_endpoint, $params);
$access_token_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,
$auth_token);
$after_access_request = $this->doHttpRequest($access_token_req->to_url());
$access_tokens = array();
parse_str($after_access_request,$access_tokens);
# line 234 below
$access_token = new OAuthConsumer($access_tokens['oauth_token'], $access_tokens['oauth_token_secret']);
// prepare for get profile call
$profile_req = $access_token_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$profile_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($profile_req->to_url());
var_dump($after_request);
}
The function var_dumps a string, which is the basic synopsis of my profile:
string(402) " User Name etc. etc. http://www.linkedin.com/profile?viewProfile=&key=28141694&authToken=HWBC&authType=name&trk=api*a137731*s146100* "
That's good. However, the minute I refresh the page, the same function call fails with:
Undefined index: oauth_token, line number: 234
(this line marked with comment in above code block).
Then, of course, the var_dump reports this error from LinkedIn:
string(290) " 401 1310652477038 R8MHA2787T 0 [unauthorized]. The token used in the OAuth request is not valid. "
something to note:
the user token, secret, and verifier are persisted during the initial authorization callback (right before this function is called). So, they are the same during the first call (when it works, right after coming back from linkedin) and during a page reload (when it fails on line 234).
Also, I must admit I'm not 100% sure I understand everything that's going on in this function. I actually took examples from this tutorial (about a different service, not linkedin) http://apiwiki.justin.tv/mediawiki/index.php/OAuth_PHP_Tutorial and combined it with the information I gathered from the LinkedIn API documentation, spread throughout their developer site. Most notable was the addition of the 'verifier' which the tutorial did not use.
Any insight into this problem would be greatly appreciated. Thanks in advance.
-Nick
UPDATE
The only way I've been able to get this going is to do a new OAuth handshake every single time. Is this the way it's supposed to happen? I was under the impression that once I got my user token/secret and verifier, that I could then use these for continuous API calls until the token expired or was revoked.
As it is now, every time the page reloads I'm requesting a new user token, secret and verifier, then immediately calling to get the user profile (which succeeds). Next reload, I get a whole new key/secret and verifier. Seems like quite a lot of work for each call, and as I understood it, you should be able to perform offline operations with this method - and if I need new authorization each time, then I guess I can't do that?
Well. I've finally figured out what was going on so thought I'd post the answer here, just in case someone else runs into this.
The example that I was using as a guide was flawed. After the access token is retrieved, you should then create a new OAuthRequest object, instead of using the existing $access_token_req instance.
So this:
// prepare for get profile call
$profile_req = $access_token_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$profile_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($profile_req->to_url());
Should be changed to this:
$api_req = new OAuthRequest("GET", $this->api_url.$api_call);
// prepare for get profile call
$api_req = $api_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$api_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($api_req->to_url());
Using Facebook's PHP SDK, I was able to get Facebook login working pretty quickly on my website. They simply set a $user variable that can be accessed very easily.
I've had no such luck trying to get Twitter's OAuth login working... quite frankly, their github material is confusing and useless for someone that's relatively new to PHP and web design, not to mention that many of the unofficial examples I've tried working through are just as confusing or are outdated.
I really need some help getting Twitter login working--I mean just a basic example where I click the login button, I authorize my app, and it redirects to a page where it displays the name of the logged in user.
I really appreciate your help.
EDIT I'm aware of the existence of abraham's twitter oauth but it provides close to no instructions whatsoever to get his stuff working.
this one is the basic example of getting the url for authorization and then fetching the user basic info when once u get back from twitter
<?php
session_start();
//add autoload note:do check your file paths in autoload.php
require "ret/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//this code will run when returned from twiter after authentication
if(isset($_SESSION['oauth_token'])){
$oauth_token=$_SESSION['oauth_token'];unset($_SESSION['oauth_token']);
$consumer_key = 'your consumer key';
$consumer_secret = 'your secret key';
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
//necessary to get access token other wise u will not have permision to get user info
$params=array("oauth_verifier" => $_GET['oauth_verifier'],"oauth_token"=>$_GET['oauth_token']);
$access_token = $connection->oauth("oauth/access_token", $params);
//now again create new instance using updated return oauth_token and oauth_token_secret because old one expired if u dont u this u will also get token expired error
$connection = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token['oauth_token'],$access_token['oauth_token_secret']);
$content = $connection->get("account/verify_credentials");
print_r($content);
}
else{
// main startup code
$consumer_key = 'your consumer key';
$consumer_secret = 'your secret key';
//this code will return your valid url which u can use in iframe src to popup or can directly view the page as its happening in this example
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" =>'http://dev.crm.alifca.com/twitter/index.php'));
$_SESSION['oauth_token']=$temporary_credentials['oauth_token']; $_SESSION['oauth_token_secret']=$temporary_credentials['oauth_token_secret'];$url = $connection->url("oauth/authorize", array("oauth_token" => $temporary_credentials['oauth_token']));
// REDIRECTING TO THE URL
header('Location: ' . $url);
}
?>
I just tried abraham's twitteroauth from github and it seems to work fine for me. This is what I did
git clone https://github.com/abraham/twitteroauth.git
Upload this into your webhost with domain, say, www.example.com
Go to Twitter Apps and register your application. The changes that you need are (assuming that you will use abraham's twitteroauth example hosted at http://www.example.com/twitteroauth)
a) Application Website will be http://www.example.com/twitteroauth
b) Application type will be browser
c) Callback url is http://www.example.com/twitteroauth/callback.php (Callback.php is included in the git source)
Once you do this, you will get the CONSUMER_KEY and CONSUMER_SECRET which you can update in the config.php from the twitteroauth distribution. Also set the callback to be the same as http://www.example.com/twitteroauth/callback.php
Thats it. If you now navigate to http://www.example.com/twitteroauth, you will get a "Signin with Twitter", that will take you to Twitter , authorize the request and get you back to the index.php page.
EDIT:
Example will not work but do not worry. Follow the above steps and upload to server.
Make sure you rename the file from github repository i.e. config-sample.php->config.php
if you want to see a working sample, find it here
Here are some OAuth 1.0A PHP libraries with examples:
tmhOAuth
Oauth-php
Twitter async
Twitter async provides documentation on how to simply sign in a user as you asked for.
Here is the step by step guide to integrate Twitter OAuth API to Web-application using PHP. Please following tutorial.
http://www.smarttutorials.net/sign-in-with-twitter-oauth-api-using-php/
You need to create Twitter App First By going thorugh following URL
https://apps.twitter.com/
Then you need to provide necessary information for the twitter app. Once your provided all the information and then save it. You will get Twitter application Consumer Key and Consumer secret.
Please download the source file from above link, and just replace TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET and TWITTER_OAUTH_CALLBACK with your Consumer Key (API Key), Consumer Secret (API Secret) and callback URL. Then upload this to your server. Now it will work successfully.
Abraham's Twitteroauth has a working demo here:
https://github.com/abraham/twitteroauth-demo
Following the steps in the demo readme worked for me. In order to run composer on macOS I had to do this after installing it: mv composer.phar /usr/local/bin/composer
IMO the demo could be a lot simpler and should be included in the main twitteroauth repo.
I recently had to post new tweets to Twitter via PHP using V2 of their API but couldn’t find any decent examples online that didn’t use V1 or V1.1. I eventually figured it out using the great package TwitterOAuth.
Install this package via composer require abraham/twitteroauth first (or manually) and visit developer.twitter.com, create a new app to get the credentials needed to use the API (see below). Then you can post a tweet based on the code below.
use Abraham\TwitterOAuth\TwitterOAuth;
// Connect
$connection = new TwitterOAuth($twitterConsumerKey, // Your API key
$twitterConsumerSecret, // Your API secret key
$twitterOauthAccessToken, // From your app created at https://developer.twitter.com/
$twitterOauthAccessTokenSecret); // From your app created at https://developer.twitter.com/
// Set API version to 2
$connection->setApiVersion('2');
// POST the tweet; the third parameter must be set to true so it is sent as JSON
// See https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets for all options
$response = $connection->post('tweets', ['text' => 'Hello Twitter'], true);
if (isset($response['title']) && $response['title'] == 'Unauthorized') {
// Handle error
} else {
var_dump($response);
/*
object(stdClass)#404 (1) {
["data"]=>
object(stdClass)#397 (2) {
["id"]=>
string(19) "0123456789012345678"
["text"]=>
string(13) "Hello Twitter"
}
}
*/
}