Twitter API cURL命令使用CLI运行但不使用PHP cURL

时间:2016-05-03 11:07:13

标签: php api curl twitter twitter-oauth

curl --get 'https://api.twitter.com/1.1/favorites/list.json' --data 
'amp%3Bscreen_name=mehulsbhandari&count=2' --header 'Authorization: 
OAuth oauth_consumer_key="XXXXXXXXXXXXXXXX", 
oauth_nonce="32981a55de0bc80cdeac7e6e23f347a9", 
oauth_signature="XXXXXXXXXXXXXX%3D", 
oauth_signature_method="HMAC-SHA1", oauth_timestamp="1462252119", 
oauth_token="XXXXXXXXXX-XXXXXXXXXXX", 
oauth_version="1.0"' --verbose  

给我输出..如何在PHP中转换它... 我已转换但显示错误

错误:代码:32,“message”:“无法对您进行身份验证。”

1 个答案:

答案 0 :(得分:1)

你可以这样做。

  function buildBaseString($baseURI, $method, $params) {
        $r = array();
        ksort($params);
        foreach($params as $key=>$value){
            $r[] = "$key=" . rawurlencode($value);
        }
        return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
    }


    function buildAuthorizationHeader($oauth) {
        $r = 'Authorization: OAuth ';
        $values = array();
        foreach($oauth as $key=>$value)
            $values[] = "$key=\"" . rawurlencode($value) . "\"";
        $r .= implode(', ', $values);
        return $r;
    }


        $url = "https://api.twitter.com/1.1/favorites/list.json";

            $oauth_access_token = "YOURVALUE";
            $oauth_access_token_secret = "YOURVALUE";
            $consumer_key = "YOURVALUE";
            $consumer_secret = "YOURVALUE";

            $oauth = array( 'oauth_consumer_key' => $consumer_key,
                            'oauth_nonce' => time(),
                            'oauth_signature_method' => 'HMAC-SHA1',
                            'oauth_token' => $oauth_access_token,
                            'oauth_timestamp' => time(),
                            'oauth_version' => '1.0');

            $base_info = buildBaseString($url, 'GET', $oauth);
            $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
            $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
            $oauth['oauth_signature'] = $oauth_signature;

            // Make requests
            $header = array(buildAuthorizationHeader($oauth), 'Expect:');
            $options = array( CURLOPT_HTTPHEADER => $header,
                              //CURLOPT_POSTFIELDS => $postfields,
                              CURLOPT_HEADER => false,
                              CURLOPT_URL => $url,
                              CURLOPT_RETURNTRANSFER => true,
                              CURLOPT_SSL_VERIFYPEER => false);

            $feed = curl_init();
            curl_setopt_array($feed, $options);
            $json = curl_exec($feed);
            curl_close($feed);

            $twitter_data = json_decode($json);

        //print it out
        print_r ($twitter_data);