Facebook Ads API Invalid OAuth access token

2019-07-13 19:39发布

We are currently trying to setup an Ads API in Laravel. It has been days but the getAdAccounts() call always results in 'Invalid OAuth access token.' exception. However same access token when used in the Graph Explorer API works just as well for the adaccounts endpoint

Here is the code -

try {
        $fb = new Facebook([
                env('FACEBOOK_APP_ID'), // App ID
                env('FACEBOOK_APP_SECRET'),
                env('FACEBOOK_GRAPH_VERSION')
                ]);

        $helper = $fb->getRedirectLoginHelper();
        $accessToken = $helper->getAccessToken();

        if (!isset($_SESSION['facebook_access_token'])) {
            $_SESSION['facebook_access_token'] = null;
        }

        if (!$_SESSION['facebook_access_token']) {
            $helper = $fb->getRedirectLoginHelper();
            try {
                $_SESSION['facebook_access_token'] = (string) $helper->getAccessToken();

            } catch(FacebookResponseException $e) {
                // When Graph returns an error
                echo 'Graph returned an error: ' . $e->getMessage();
                exit;
            } catch(FacebookSDKException $e) {
                // When validation fails or other local issues
                echo 'Facebook SDK returned an error: ' . $e->getMessage();
                exit;
            }
        }

        if ($_SESSION['facebook_access_token']) {
            echo "You are logged in!";

            Api::init(
            env('FACEBOOK_APP_ID'), // App ID
            env('FACEBOOK_APP_SECRET'),
            $_SESSION['facebook_access_token']
            );
            echo $_SESSION['facebook_access_token'];
            $me = new AdUser('me');
            //dd($me);
            $my_adaccount = $me->getAdAccounts();
            dd($my_adaccount);

        } else {
            $permissions = ['ads_management', 'user_friends'];
            $loginUrl = $helper->getLoginUrl('http://localhost:8000/facebookads', $permissions);
            echo '<a href="' . $loginUrl . '">Log in with Facebook</a>';
        }
    }
    catch(FacebookResponseException $e) {
        // When Graph returns an error
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    } catch(FacebookSDKException $e) {
        // When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }
    catch(\Exception $e){

        dd($e);
    }

1条回答
三岁会撩人
2楼-- · 2019-07-13 20:29

Api::init(APP_ID,APP_SECRET, ACCESS_TOKEN); ACCESS_TOKEN Not refer to $_SESSION['facebooke_access_token'] but your Marketing API token. Go to https://developers.facebook.com/apps//marketing-api/tools/ to get Marketing API token.

查看更多
登录 后发表回答