doucheng4094 2013-08-09 10:07
浏览 43
已采纳

Twitter app-only auth适用于localhost,但不适用于服务器

I'm using the app-only auth for Twitter and trying to get search results. I'm using Codeigniter for the most part, but the code in question is just plain PHP.

It happily returns search results when I'm running it on my localhost, but running it on my server gives me the following error:

[code] => 99 [label] => authenticity_token_error [message] => Unable to verify your credentials

So it's failing at the first request to get my bearer token.

This seems a bit screwy to me and is obviously hard to debug. I'm probably missing something quite basic, so any help would be gratefully accepted!

Below is my code:

    // get consumer key and consumer secret from my config files
    $consumer = array(
        'key' => $this->config->item($provider.'_key'),
        'secret' => $this->config->item($provider.'_secret'),
    );

    // encode it into the format Twitter expects
    $bearerTokenCred = base64_encode($consumer['key'].":".$consumer['secret']);

    // set up request
    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  =>    'Authorization: Basic '.$bearerTokenCred."
".
                            "Content-type: application/x-www-form-urlencoded;charset=UTF-8
",
            'content' => 'grant_type=client_credentials'
        )
    );

    $context  = stream_context_create($opts);

            // send request
    $result = file_get_contents('https://api.twitter.com/oauth2/token', false, $context);

    $result2 = json_decode($result, true);

            // this is where it prints my error - prior to doing anything else
    print_r($result2);

    if ($result2["token_type"] != "bearer"){
        echo $result2["token_type"];
        return;
    }

    $opts = array('http' =>
        array(
            'method'  => 'GET',
            'header'  => 'Authorization: Bearer '.$result2["access_token"]       
        )
    );

    $context  = stream_context_create($opts);

    $result3 = file_get_contents('https://api.twitter.com/1.1/search/tweets.json?q='.urlencode($search), false, $context);
  • 写回答

1条回答 默认 最新

  • dongtuanzi1080 2013-08-22 14:59
    关注

    I haven't actually managed to solve the problem as stated, but went on a few goose-chases concerning the use of strings vs arrays in the sent header (http://www.php.net/manual/en/function.stream-context-create.php#99353) - which still didn't do anything for me.

    In the end I resorted to using CURL which did the job.

    My assumption is that it's something to do with my server configuration, but I couldn't tell you what!

    Final working code below

        $provider = 'twitter';
    
        // Get keys from the config
        $consumer = array(
            'key' => $this->config->item($provider.'_key'),
            'secret' => $this->config->item($provider.'_secret'),
        );
        $bearerTokenCred = base64_encode($consumer['key'].":".$consumer['secret']);
    
        $data = array ('grant_type' => 'client_credentials');
        $data = http_build_query($data);
    
        $header = array(
            "Authorization: Basic $bearerTokenCred",
            "Content-type: application/x-www-form-urlencoded;charset=UTF-8",
            "Content-Length: " . strlen($data) 
        );
    
        $options = array( 
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_HEADER => false,
            CURLOPT_URL => "https://api.twitter.com/oauth2/token",
            CURLOPT_RETURNTRANSFER => true
        );
    
        $options[CURLOPT_POSTFIELDS] = $data;
    
        $feed = curl_init();
        curl_setopt_array($feed, $options);
        $result = curl_exec($feed);
        curl_close($feed);
    
        $result2 = json_decode($result, true);
    
        if ($result2["token_type"] != "bearer"){
            echo "error - invalid token type";
            return;
        }
    
        $header = array(
            'Authorization: Bearer '.$result2["access_token"]
        );
    
        $options = array( 
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_HEADER => false,
            CURLOPT_URL => 'https://api.twitter.com/1.1/search/tweets.json?q='.urlencode('"#'.$search.'"'),
            CURLOPT_RETURNTRANSFER => true
        );
    
        $feed = curl_init();
        curl_setopt_array($feed, $options);
        $result = curl_exec($feed);
        curl_close($feed);
    
        $result3 = json_decode($result, true);
    
        foreach($result3['statuses'] as $status){
            echo "<p>".$status['text']."</p>";
        }
    

    I hope this is of use to someone out there!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路