Facebook OAuth,wp_http::Request()与wp_Remote_Request()

时间:2012-04-23 作者:soderlind

运行WordPress 3.3.2和PHP版本5.2.17

我正在尝试使用wp\\u remote\\u request()和Facebook OAuth API(顺便说一句,本条目末尾的工作示例)从Facebook获取access\\u令牌。

是否有任何原因导致此操作不起作用(应根据文档和源代码)

$response = wp_remote_request(\'https://graph.facebook.com/oauth/access_token\', array(           
        \'timeout\' => 60,
        \'sslverify\' => false,
        \'method\' => \'GET\',
        \'body\' =>  array( 
                \'client_id\' => FACEBOOK_APPID, 
                \'client_secret\' => FACEBOOK_APPSECRET,
                \'redirect_uri\' => REDIRECTURI,
                \'code\' => $_GET[\'code\']
        )
));
什么时候会这样?:

$http = new WP_Http;

$api_url = sprintf("https://graph.facebook.com/oauth/access_token?client_id=%s&redirect_uri=%s&client_secret=%s&code=%s",
    urlencode(FACEBOOK_APPID),
    urlencode(REDIRECTURI),
    urlencode(FACEBOOK_APPSECRET),
    urlencode($_GET[\'code\'])
);
$response = $http->request($api_url, array(\'timeout\' => 60, \'sslverify\' => false));
工作示例:

<?php
/* Short and sweet */
define(\'WP_USE_THEMES\', false);
require(\'../wp-blog-header.php\');
?>
<?php
define(\'FACEBOOK_APPID\',\'123\'); // replace 123 with your app id
define(\'FACEBOOK_APPSECRET\',\'abc\'); // replace abc with your app secret

define(\'REDIRECTURI\',\'http://your.redirect.url\');

if ($_GET[\'code\'] != \'\') {
    if ($_GET[\'state\'] != \'\' && wp_verify_nonce($_GET[\'state\'], \'my-nonce\')) { 

        $http = new WP_Http;

        $api_url = sprintf("https://graph.facebook.com/oauth/access_token?client_id=%s&redirect_uri=%s&client_secret=%s&code=%s",
            urlencode(FACEBOOK_APPID),
            urlencode(REDIRECTURI),
            urlencode(FACEBOOK_APPSECRET),
            urlencode($_GET[\'code\'])
        );
        $response = $http->request($api_url, array(\'timeout\' => 60, \'sslverify\' => false));

        if( is_wp_error( $response ) ) {
           echo \'ERROR\';
        } else {
            $args = wp_parse_args( wp_remote_retrieve_body($response), array() );
            echo $args[\'access_token\']; 
        }
    }   
} else {
     $facebook_dialog_url = sprintf("https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&state=%s", 
        FACEBOOK_APPID, 
        urlencode(REDIRECTURI),
        wp_create_nonce (\'my-nonce\')
     ); 


    echo \'<a href="\'. $facebook_dialog_url .\'">LOGIN TO FACEBOOK</a> <br />\';
}
?>

2 个回复
SO网友:soderlind

要回答我自己的问题,当您使用WP\\U Http时,将按照以下顺序从该阵列中选择所使用的传输:$request_order = array( \'curl\', \'streams\', \'fsockopen\' );

如果您的PHP支持curl,则使用WP\\u Http\\u curl。Curl不支持添加body数组参数when the method is GET

另一方面,WP\\u Http\\u Streams和WP\\u Http\\u Fsockopen添加body数组参数。

SO网友:Rarst

body 参数用于POST请求并在标头中设置。对于GET请求,请将请求参数编码到URL中(如第二个代码段所示)。

结束