emersonbroga
11/27/2012 - 8:40 PM

Find Facebook Current User

Find Facebook Current User

    function getFacebookCurrentUserId( $secret = null )
    {
    	$data = getFacebookCurrentUser($secret);
    	
    	return (isset($data['user_id'])) ? $data['user_id'] : null;
    	
    }
    
    function getFacebookCurrentUser( $secret = null )
    {
    	
    	//https://developers.facebook.com/docs/howtos/login/signed-request/
    	
		if( !isset($_REQUEST['signed_request']) )
			return null;
		
		$signed_request = $_REQUEST['signed_request'];	
			
		list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
		// decode the data
		
		$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
		$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);

		if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
	    	return null;
    	}

    	if($secret){
  			// Adding the verification of the signed_request below
  			$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
			if ($sig !== $expected_sig) {
				return null;
			}
    	}
    	
    	return $data;
	}