Facebook OAuth, WP_Http::request() vs wp_remote_request()

Running WordPress 3.3.2 and PHP Version 5.2.17

I’m trying to get the access_token from Facebook using wp_remote_request() and Facebook OAuth API (btw, working example at the end of this entry).

Read More

Is there any reason why this doesn’t work (should according to doc and source code)?:

$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']
        )
));

When this does?:

$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));

Working example:

<?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 />';
}
?>

Related posts

Leave a Reply

2 comments