I wrote a script that asks Twitter for authorization. If the script runs the first time, it will be redirected to Twitter and then the credentials will be saved to a json file. This works. But the authorization page from twitter will be loaded two times. Perhaps somebody can help me to find the bug. Here is the script:
require('./vendor/autoload.php');
use TijsVerkoyen\Twitter\Twitter;
$twitter = new Twitter('xyz', 'xyz');
$response = $twitter->oAuthRequestToken('http://localhost:8888/tweeted-news/oauth-test.php');
$credentials = json_decode(file_get_contents('credentials.json'), true);
if (!isset($credentials['oauth_token'])) {
$response = $twitter->oAuthAuthorize($response['oauth_token']);
$response = $twitter->oAuthAccessToken($_GET['oauth_token'], $_GET['oauth_verifier']);
file_put_contents('credentials.json', json_encode($response));
var_dump('authorized');
} else {
$twitter->setOAuthToken($credentials['oauth_token']);
$twitter->setOAuthTokenSecret($credentials['oauth_token_secret']);
var_dump('credentials');
}
var_dump($twitter->accountSettings());
I'm using this library https://github.com/tijsverkoyen/TwitterOAuth with composer. Thanks a lot.
Remove the else line. After the var_dump('authorized'), you should be setting the OAuthToken and OAuthTokenSecret. So the code should read:
if (!isset($credentials['oauth_token'])) {
$response = $twitter->oAuthAuthorize($response['oauth_token']);
$response = $twitter->oAuthAccessToken($_GET['oauth_token'], $_GET['oauth_verifier']);
file_put_contents('credentials.json', json_encode($response));
var_dump('authorized');
$twitter->setOAuthToken($credentials['oauth_token']);
$twitter->setOAuthTokenSecret($credentials['oauth_token_secret']);
var_dump('credentials');
}