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).
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 />';
}
?>
To answer my own question, when you use WP_Http, the transport used is selected, in this order, from this array:
$request_order = array( 'curl', 'streams', 'fsockopen' );
If your PHP supports curl, WP_Http_Curl is used. Curl doesn’t support adding the body array parameters when the method is GET
WP_Http_Streams and WP_Http_Fsockopen on the other hand, add the body array parameters.
body
argument is used for POST requests and set in headers. For GET request encode request arguments into URL (as in your second snippet).