Sometimes works oauth/access_token by the oauth_verifier and other times not work



I have implemented the OAuth request in my system. In brief the system that we are developing is a Social Media Manager System, the idea is the Community Managers add their Twitter accounts in our system. But when I try to add an account sometimes works and other times not works.

First of all I create the login url

$twitter->setTimeouts(10, 10);

$request_token = $twitter->oauth('oauth/request_token', array('oauth_callback' => 'CALLBACK URL'));

$url = $twitter->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token'])); 
$this->view->assign('urlLoginTwitter', $url]); //This is for send to view the link

//Save the temporal tokens, it will use in next steps
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  ' . $my_file);
$data = $request_token['oauth_token'] . '&' . $request_token['oauth_token_secret'];
fwrite($handle, $data);

Later the user click the url, authenticate in twitter and the moment of callback

$currentUrl = $this->uriBuilder->getRequest()->getRequestUri(); //Get the url of browser with oauth_token and oauth_verifier
$urlParts = explode('&', $currentUrl);
$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle, filesize($my_file));
$request_token = explode('&', $data);

$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $request_token[0], $request_token[1]);
$oauthVerifier = explode('=', $urlParts[2]);
try {    
        $accessTokensThisPerfil = $twitter->oauth('oauth/access_token', array("oauth_verifier" => "$oauthVerifier[1]"));
        } catch (\Exception $exception) {    
            $logger = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Core\Log\LogManager')->getLogger(__CLASS__);
            $logger->error('TWITTER add', array('data' => $exception->getMessage()));

How I say, sometimes the “echo” is “WORKS” and others “FAIL”. When I write in the log, the error is

Error processing your OAuth request: Invalid oauth_verifier parameter

I understand the problem is de outh_verified that I get from the URL in callback. But I do not know why works and not works randomly.

Please guide me or illustrate me what may be happening


Are you confident that $urlParts[2] always contains the oauth_verifier=codehere returned to the callback? If the params are ever in a different order this will break.

Try putting all the url params into an associative array instead, then you can call by name and handle if not set:

$currentUrl = "foo=bar&alice=bob&blank";

$urlPartsArr = explode('&', $currentUrl); // like ["foo=bar", "alice=bob" "blank"]
$requestGETParams = array();
foreach($urlPartsArr as $element){
	$left = explode("=", $element)[0];
	$right = (isset(explode("=", $element)[1])?explode("=", $element)[1]:"");
	$requestGETParams[$left] = $right;

// "bar"

// array(3) {
// 		["foo"]=> string(3) "bar"
// 		["alice"]=> string(3) "bob"
// 		["blank"]=> string(0) ""
// 	}


Yes, I am sure. I tried to modify the array as yo recommended me. The result is this:

//array (size=3) { 
//  '' => string '15' (length=2)
//  'oauth_token' => string '0c91RQAAAAAAy3sjAAABYFqqhh0' (length=27)
//  'oauth_verifier' => string 'R4SQ8rLfD8dgsNxyKEZTpTbn1DaVUtlt' (length=32)
// }
$twitter->oauth('oauth/access_token', array("oauth_verifier" => '$requestGETParams['oauth_verifier']'));

//The value sent as parameter in the above line is the 'oauth_verifier' inside the response of Twitter in callback.


Is that an exact copy of the code?

I would expect:

array("oauth_verifier" => '$requestGETParams['oauth_verifier']')

To be a syntax error, as single quotes will treat its contents as an exact string. Does:

array("oauth_verifier" =>  $requestGETParams['oauth_verifier'] )

Fail also?


Not, the code above is a sumary of program, a code copy is the next:

$accessTokensThisProfile = $adapterTwitter->getAccessToken($requestGETParams['oauth_verifier']); 

‘$adapterTwitter’ is an instance of class TwitterAdapter that use an attribute calls ‘api’ as instance of TwitterAdapter()

$this->api =  new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret); 

And fuction of ‘getAccessToken’ is:

 public function getAccessToken($oauthVerifier){
    	 $accesToken = $this->api->oauth('oauth/access_token', array("oauth_verifier" => "$oauthVerifier"));
    	 return $accesToken;

Inside this I have the " " for oauth verifier; I removed these but the funcionality is the same. Randomly works and not work.