skip to Main Content

I’m using the code below on my website to try and post a message on a Facebook page that I manage. I’m using the Facebook PHP SDK v5. Whenever I run the code I get directed to Facebook with an error window that says,

“URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.”

However, if I go to the Graph API Explorer and request a User Access Token, then hard code the access token into the script it works just fine. I added Facebook Login to the products tab on my app setting, since that’s the only place you can add in the “Valid OAuth redirect URIs”. I’m pretty sure the problem is coming from the “Valid OAuth redirect URIs” field in the setting area. I’m not sure what to put in that field or if that is even the problem at all. Currently, I’ve tried putting the following in the “Valid OAuth redirect URIs” field with no luck;

  1. just my domain i.e. www.my-domain.com

  2. the full path the the calling script i.e. www.my-domain.com/calling-script.php

  3. the full path to a blank page on my server i.e. www.my-domain.com/blank.html

None are working. This is my first go at trying to use the Facebook PHP SDK so I’m sure I’m doing it all wrong… Wondering if anyone is able to give me some guidance on this?

UPDATE:
See answer posted below with fix. My original post was not very clear regarding my intentions. My goal was to successfully post a message to a Facebook Page as the Page, not as an individual user. Hope this helps someone down the road.

Here are my app settings:
Main App Settings

Facebook Login Settings

Here is the PHP script I am using:

session_start();
$path = "path-to-Facebook-autoloader-on-my-server";
include_once $path;

$fb = new FacebookFacebook([
  'app_id' => 'app-id-from-app-settings',
  'app_secret' => 'app-secret-number-from-app-settings',
  'default_graph_version' => 'v2.7',
]);
/////////////////////////////////////////////////////////////////////////
//  If I uncomment the below line the script works fine, but the token expires often 
//  and I do not want to have to keep updating it  
//  $_SESSION['facebook_access_token'] = "access-token-obtained-from-Graph-API-Explorer";
/////////////////////////////////////////////////////////////////////////
$helper = $fb->getCanvasHelper();
$permissions = ['email', 'publish_actions']; // optional
try {
    if(isset($_SESSION['facebook_access_token'])){
        $accessToken = $_SESSION['facebook_access_token'];
    }else{
        $accessToken = $helper->getAccessToken();
    }
}catch(FacebookExceptionsFacebookResponseException $e){
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
}catch(FacebookExceptionsFacebookSDKException $e){
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}
if(isset($accessToken)){
    if(isset($_SESSION['facebook_access_token'])){
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }else{
        $_SESSION['facebook_access_token'] = (string)$accessToken;
        // OAuth 2.0 client handler
        $oAuth2Client = $fb->getOAuth2Client();
        // Exchanges a short-lived access token for a long-lived one
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
        $_SESSION['facebook_access_token'] = (string)$longLivedAccessToken;
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }

    // validating the access token
    try{
        $request = $fb->get('/me');
    }catch(FacebookExceptionsFacebookResponseException $e){
        // When Graph returns an error
        if($e->getCode() == 190){
            unset($_SESSION['facebook_access_token']);
            $helper = $fb->getRedirectLoginHelper();
            $loginUrl = $helper->getLoginUrl('https://apps.facebook.com/austintestingapp/', $permissions);
            echo "<script>window.top.location.href='".$loginUrl."'</script>";
            exit;
        }
    }catch(FacebookExceptionsFacebookSDKException $e){
        // When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }

    try{
        // message must come from the user-end
        $data = ['message' => 'test message...'];
        $request = $fb->post('/me/feed', $data);
        $response = $request->getGraphNode();
    }catch(FacebookExceptionsFacebookResponseException $e){
        // When Graph returns an error
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    }catch(FacebookExceptionsFacebookSDKException $e){
        // When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }

    echo $response['id'];

}else{
    $helper = $fb->getRedirectLoginHelper();
    $loginUrl = $helper->getLoginUrl('https://apps.facebook.com/austintestingapp/', $permissions);
    echo "<script>window.top.location.href='".$loginUrl."'</script>";
}

2

Answers


  1. Chosen as BEST ANSWER

    So I ended up figuring it out. I played around with the script I originally posted and finally got it to work...sort of. No matter how I ran the script messages were always being sent to the page I manage as a notification. They would not show up on the wall. The end goal I was looking for was to post on to a page that I manage as the page, not as myself. Just in case anyone else comes across this the code below works perfect. Also, it does not require you to submit privileges for approval with Facebook.

    The answer to my original question in regards to the "Valid OAuth redirect URIs" field. I ended up putting the path to the calling script in that field and it worked fine.

    session_start();
    $path = "server-path-to-Facebook-autoloader.php";
    $permissions = ['manage_pages', 'publish_pages'];
    $callback = "full-path-to-the-calling-script(this-script).php";
    include_once $path;
    
    $fb = new FacebookFacebook([
      'app_id' => 'app-id-number-here',
      'app_secret' => 'app-secret-here',
      'default_graph_version' => 'v2.7',
    ]);
    
    $helper = $fb->getRedirectLoginHelper();
    
    try {
        if (isset($_SESSION['facebook_access_token'])) {
            $accessToken = $_SESSION['facebook_access_token'];
        } else {
            $accessToken = $helper->getAccessToken();
        }
    } catch(FacebookExceptionsFacebookResponseException $e) {
        // When Graph returns an error
        $res['myresponse'] = 'Error: Graph returned a session error: ' . $e->getMessage();
        echo $res['myresponse'];
        exit;
    } catch(FacebookExceptionsFacebookSDKException $e) {
        // When validation fails or other local issues
        $res['myresponse'] = 'Error: Facebook SDK returned a session error: ' . $e->getMessage();
        echo $res['myresponse'];
        exit;
     }
    
    if (isset($accessToken)) {
        if (isset($_SESSION['facebook_access_token'])) {
            $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
        } else {
            // getting short-lived access token
            $_SESSION['facebook_access_token'] = (string) $accessToken;
    
            // OAuth 2.0 client handler
            $oAuth2Client = $fb->getOAuth2Client();
    
            // Exchanges a short-lived access token for a long-lived one
            $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
    
            $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
    
            // setting default access token to be used in script
            $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
        }
    
        // getting basic info about user
        try {
            $profile_request = $fb->get('/me');
            $profile = $profile_request->getGraphNode();
        } catch(FacebookExceptionsFacebookResponseException $e) {
            // When Graph returns an error
            $res['myresponse'] = 'Error: Graph returned a profile request error: ' . $e->getMessage();
            echo $res['myresponse'];
            session_destroy();
            // redirecting user back to app login page
            header("Location: ./");
            exit;
        } catch(FacebookExceptionsFacebookSDKException $e) {
            // When validation fails or other local issues
            $res['myresponse'] = 'Error: Facebook SDK returned a profile request error: ' . $e->getMessage();
            echo $res['myresponse'];
            exit;
        }
    
        // post on behalf of page
        $pages = $fb->get('/me/accounts');
        $pages = $pages->getGraphEdge()->asArray();
    
        foreach ($pages as $key) {
            if ($key['name'] == 'name-of-page-to-post-to') {
                $post = $fb->post('/' . $key['id'] . '/feed', array('message' => 'this is an automated test message from Affordable HomeCare...'), $key['access_token']);
                $post = $post->getGraphNode()->asArray();
                if($post['id'] <> ''){
                    $res['myresponse'] = "Successfully Posted to Facebook";
                }else{
                    $res['myresponse'] = "Error: Unable to verify post ID";
                }
                echo $res['myresponse'];
            }
        }
    } else {
        $loginUrl = $helper->getLoginUrl($callback, $permissions);
        echo "<script>window.top.location.href='".$loginUrl."'</script>";
    }
    

  2. i checked your script. all looks fine except one thing. can u try after changing

    $helper = $fb->getCanvasHelper();
    

    to

    $helper = $fb->getRedirectLoginHelper();
    

    and see what error it throws if any?
    also u can refer to the shared gist. do let us know your error.
    https://gist.github.com/gunnrryy/c2c828fc2a77124cc1bed57af5e216df

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search