0

我正在尝试在 wordpress 中使用 oauth 从 facebook 获取用户数据。我在插件文件中有以下代码,

class fb{
    function authenticate($req){
define('FACEBOOK_APPID','xxxxx'); // replace 123 with your app id
define('FACEBOOK_APPSECRET','xxxxxx'); // replace abc with your app secret
define('REDIRECTURI','http://test.name.com/index.php?request=facebookdata_Action'); 
   if ($_REQUEST['code'] != '') {
    if ($_REQUEST['state'] != '' && wp_verify_nonce($_REQUEST['state'], 'my-nonce')) {

        $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($_REQUEST['code'])
        );

        $response = wp_remote_request($api_url, array(
            'timeout' => 60,
            'sslverify' => false,
            'method' => 'GET'
        ));

        if( is_wp_error( $response ) ) {
          $messages['error'] = "There was an error.";
        } else {
            $args = wp_parse_args( wp_remote_retrieve_body($response), array() );
            //echo $args['access_token'];
            $messages['userdata'] = $args;
        }
    }
} else {
     $facebook_dialog_url = sprintf("https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&state=%s&scope=user_photos,email,user_birthday,user_online_presence",
        FACEBOOK_APPID,
        urlencode(REDIRECTURI),
        wp_create_nonce ('my-nonce')
     );
  $messages['url'] = trim($facebook_dialog_url);

}
     echo json_encode($messages);
       exit();
    }
}

// 处理 AJAX 请求的函数

function Request_handler() {
if (isset($_REQUEST['request']) && ($_REQUEST['request'] == 'facebook_Action')) {
        // Otherwise display an error and exit the call
        $obj = new fb();
        echo $obj->authenticate($_REQUEST);
        exit();
    }   
}

// 将处理程序添加到 init()

add_action('init', 'Request_handler');

当我单击按钮时,我facebook_Action使用将调用此authenticate函数的 ajax 调用它,最后我得到了facebook url. 我使用 window.location 重定向到 facebook 登录页面。

登录后,我被重定向到我的页面。我得到了访问令牌作为响应。我要求获取email,gender,phone number作为响应的用户数据。

请就此提出建议

4

1 回答 1

0

我参考了这个http://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/

通过使用 access_token 找到了解决方案

// Attempt to query the graph:
  $graph_url = "https://graph.facebook.com/me?"
    . "access_token=" . $access_token;
  $response = curl_get_file_contents($graph_url);
  $decoded_response = json_decode($response);

function curl_get_file_contents($URL) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_URL, $URL);
    $contents = curl_exec($c);
    $err  = curl_getinfo($c,CURLINFO_HTTP_CODE);
    curl_close($c);
    if ($contents) return $contents;
    else return FALSE;
  }
于 2012-06-29T07:25:06.700 回答