简体   繁体   中英

Twitter API v1.1 redirect to application does not work

I'm a newbie with Twitter API and I'm trying to fetch the user timeline data in my application.

I have set the application settings and config.php file correctly, so the user logs in successfully and sees the "Redirecting back to your application" message, but after redirecting to http://MyDomainName.com/callback.php?oauth_token=someToken&oauth_verifier=someOtherToken the page does not show up in the browser and redirecting does not happen. Coming back to application page manually, the user is not logged in and must login again. Can anyone please help me with this?

Config.php

/**
 * @file
 * A single location to store configuration.
 */

define('CONSUMER_KEY', 'ALPHA_NUMERIC_CONSUMER_KEY');
define('CONSUMER_SECRET', 'ALPHA_NUMERIC_SECRET');
define('OAUTH_CALLBACK', "http://infosys.concordia.ca/MyApps/oauthProxy/callback.php");
define('OAUTH_COOKIE', 'my_twitter_app_oauth');
define('OAUTH_COOKIE_DOMAIN', '.concordia.ca'); //Example ".esri.com"
echo OAUTH_CALLBACK;

//REQUIRED - Encrypt your cookies
//http://si0.twimg.com/images/dev/oauth_diagram.png
//Create your own unique ENCRYPTION_KEY via Encrypt.get_RandomKey()
define('ENCRYPTION_KEY','MY_UNIQUE_ENCRYPTION_KEY'); 
//Create your own unique initialization vector via Encrypt.get_IV()
define('IV','MY_UNIQUE_IV');
define('DEFAULT_TIME_ZONE','America/Toronto');

Callabck.php

<?php

//Version 2.1 by AndyG 4/2013
//Changes
//- added OAuth Encrption

// Start session and load lib
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('twitteroauth/Encrypt.php');
require_once('config.php');

$content = null;    //for verification of credentials
$connection = null; //for getting access token

// check if cookie exists
if(isset($_COOKIE[OAUTH_COOKIE])){
    // redirect back to app
    if(isset($_SESSION['oauth_referrer'])){
        header('Location: '.$_SESSION['oauth_referrer']);
        exit;
    }
}
else{
    // if verifier set
    if(isset($_REQUEST['oauth_verifier'])){

        //Best practice is to encrypt the cookies or not use cookies
        $key = base64_decode(ENCRYPTION_KEY);
        $iv = base64_decode(IV);
        $encrypt = new Encrypt($key,$iv,DEFAULT_TIME_ZONE);


        // Create TwitteroAuth object with app key/secret and token key/secret from default phase
        $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

        // get access token from twitter
        try{
            $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
        }
        catch(Exception $e){
            header("HTTP/1.0 400 Error");
            echo "\n\nFailed retrieving access token: " .$e->getMessage();
            exit;
        }

        //Add a credentials validation request. Added v2.0 by AndyG
        try{
            $content = $connection->get('account/verify_credentials','');
        }
        catch(Exception $e){
            $error = $e->getMessage();
        }
        // save token
        $_SESSION['oauth_access_token'] = $access_token;
        // 1 year
        $cookie_life = time() + 31536000;

        if($content != null && $content->screen_name != ""){

            $token = base64_encode( $encrypt->encrypt($access_token['oauth_token']));
            $token_secret = base64_encode( $encrypt->encrypt($access_token['oauth_token_secret']));     

            //Update array with new encrypted values
            $access_token["oauth_token"] = $token;
            $access_token["oauth_token_secret"] = $token_secret;
            // echo "\n\n".var_dump($access_token); //for testing

            // set cookie
            setcookie(OAUTH_COOKIE, json_encode($access_token), $cookie_life, '/', OAUTH_COOKIE_DOMAIN);
            //header('Location: ./callback.php');
            echo "<html><head><title>Valid Verification</title><body bgcolor='#C0C0C0'>";
            echo "<style type='text/css'>body{font-family:sans-serif;}</style>";
            echo "<table width='100%'><tr bgcolor='#FFFFFF'><td>";
            echo "<a href='http://www.esri.com'><img src='edn.png' style='border-style:none' alt='ESRI Developer Network' /></a>";
            echo "</td></tr></table>";
            echo "<h2>Welcome:&nbsp;&nbsp;<img src='".$content->profile_image_url."'></img>&nbsp;&nbsp;&nbsp;@".$content->screen_name."</h2>";
            echo "<h4>You have successfully authenticated with Twitter. </h4>" ;
            echo "<h4>It is okay to close this page and return to the application.</h4>";
            echo "<script language=\"JavaScript\">\n";
            echo "if(window.opener && window.opener.getTokens){";
            echo "window.opener.getTokens(\"".$_SESSION['oauth_token'].",".$_SESSION['oauth_token_secret']."\");}";
            //You can also have the app automatically close the window via self.close, as shown below
            //echo "self.close();";
            echo "</script>";
            echo "</body></html>";
        }
        else{
            header("HTTP/1.0 400 Error");
            echo "\n\nFailed to validate credentials. ".$error;
            exit;
        }
        exit;
    }
    else{
       // redirect
        if(isset($_SESSION['oauth_referrer'])){
            header('Location: '.$_SESSION['oauth_referrer']);
        }
        else{
            header('Location: '.OAUTH_CALLBACK);
        }
        exit;
    }
}

Without any code it's hard to see what you did wrong.

You have to either pass a fully qualified URL as oauth_callback when you fetch your initial request token, or hard-code a callback URL into your Twitter app settings .

If you pass in the oauth_callback I believe you have to enter a dummy value in the settings or it won't work.

My bad! The callback URL in application settings was not the same as the callback URL in config.php. Everything is working now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM