Пример #1
0
 public function __construct(ResponseInterface $response, AbstractObject $object_prototype, Api $api = null)
 {
     $this->response = $response;
     $this->objectPrototype = $object_prototype;
     $this->api = $api !== null ? $api : Api::instance();
     $this->appendResponse($response);
 }
Пример #2
0
 /**
  * @return \Facebook\FacebookSession
  */
 public function getSession()
 {
     $conf = json_decode(file_get_contents(realpath(dirname(__FILE__)) . '/config.json'));
     Api::init($conf->applicationId, $conf->applicationSecret, $conf->accessToken);
     FacebookSession::setDefaultApplication($conf->applicationId, $conf->applicationSecret);
     return new FacebookSession($conf->accessToken);
 }
Пример #3
0
 /**
  * @return \Facebook\Facebook
  */
 public function getFacebook()
 {
     $conf = json_decode(file_get_contents(realpath(dirname(__FILE__)) . '/config.json'));
     Api::init($conf->applicationId, $conf->applicationSecret, $conf->accessToken);
     $facebook = new \Facebook\Facebook(['app_id' => $conf->applicationId, 'app_secret' => $conf->applicationSecret, 'default_access_token' => $conf->accessToken, 'default_graph_version' => 'v2.4']);
     return $facebook;
 }
Пример #4
0
 /**
  * Register the application services.
  *
  * @return void
  */
 public function register()
 {
     $this->app->bind('FacebookAdsAPI', function () {
         $config = config('facebook');
         Api::init($config['app_id'], $config['app_secret'], $config['access_token']);
         return Api::instance();
     });
 }
Пример #5
0
 /**
  * Create an instance of Facebook session
  */
 private function set_fb_request_session()
 {
     $settings = array('app_id' => APP_ID_FOR_ADS_MANAGER, 'app_secret' => APP_SECRET_FOR_ADS_MANAGER, 'default_graph_version' => 'v2.5');
     $fb = new Facebook\Facebook($settings);
     $fb->setDefaultAccessToken(self::$fbToken);
     self::$fbSession = $fb;
     Api::init(APP_ID_FOR_ADS_MANAGER, APP_SECRET_FOR_ADS_MANAGER, self::$fbToken);
 }
Пример #6
0
 /**
  * @param string $query
  * @param string $type
  * @param string $class
  * @param array $params
  * @param Api $api
  * @return Cursor
  * @throws \InvalidArgumentException
  */
 public static function search($type, $class = null, $query = null, array $params = array(), Api $api = null)
 {
     $api = $api ?: Api::instance();
     if (!$api) {
         throw new \InvalidArgumentException('An Api instance must be provided as argument or ' . 'set as instance in the \\FacebookAds\\Api');
     }
     $params = array_merge($params, array('type' => $type, 'class' => $class, 'q' => $query));
     $response = $api->call('/search', RequestInterface::METHOD_GET, $params);
     return new Cursor($response, new TargetingSearch());
 }
Пример #7
0
 /**
  * @param string    $appId          Facebook app ID
  * @param string    $appSecret      Facebook app Secret
  * @param string    $fbToken        Facebook token
  * @param object    $appSettings    Application configuration settings
  * @param array     $availability   Array with current doctor availability
  * @throws Exception
  */
 public function __construct($appId, $appSecret, $fbToken, $appSettings, $availability)
 {
     if (empty($appId) || empty($appSecret) || empty($fbToken) || !is_object($appSettings)) {
         throw new Exception('All params are required');
     }
     self::$appId = $appId;
     self::$appSecret = $appSecret;
     self::$fbToken = $fbToken;
     self::$settings = $appSettings;
     self::$availability = $availability;
     $this->set_account_id();
     $this->set_fb_request_session();
     Api::init($appId, $appSecret, $fbToken);
     $this->CI =& get_instance();
 }
Пример #8
0
 public function __construct($accessToken, $appId, $appSecret, $accountId)
 {
     if (!is_string($accessToken) || !is_string($appId) || !is_string($appSecret) || !is_string($accountId)) {
         throw new Exception("Missing parameter(s)");
     }
     $this->accessToken = $accessToken;
     $this->appId = $appId;
     $this->appSecret = $appSecret;
     $this->accountId = $accountId;
     date_default_timezone_set('America/Los_Angeles');
     Api::init($this->appId, $this->appSecret, $this->accessToken);
     $this->account = (new AdAccount($this->accountId))->read([AdAccountFields::ID, AdAccountFields::ACCOUNT_STATUS]);
     if ($this->account->{AdAccountFields::ACCOUNT_STATUS} !== 1) {
         throw new \Exception('This account is not active');
     }
 }
 /**
  * @param string $query
  * @param string $type
  * @param string $class
  * @param array $params
  * @param Api $api
  * @return Cursor
  * @throws \InvalidArgumentException
  */
 public static function search($type, $class = null, $query = null, array $params = array(), Api $api = null)
 {
     $api = $api ?: Api::instance();
     if (!$api) {
         throw new \InvalidArgumentException('An Api instance must be provided as argument or ' . 'set as instance in the \\FacebookAds\\Api');
     }
     $params = array_merge($params, array('type' => $type, 'class' => $class, 'q' => $query));
     $response = $api->call('/search', Api::HTTP_METHOD_GET, $params);
     $result = array();
     foreach ($response->getResponse()->{'data'} as $data) {
         /** @var $object AbstractObject */
         $object = new static();
         if (is_object($data)) {
             $data = get_object_vars($data);
         }
         $object->setData($data);
         $result[] = $object;
     }
     return new Cursor($result, $response);
 }
Пример #10
0
 private function init_ads_api_instance($fbToken)
 {
     Api::init(APP_ID_FOR_ADS_MANAGER, APP_SECRET_FOR_ADS_MANAGER, $fbToken);
 }
Пример #11
0
 private function initFacebookApi($accessToken)
 {
     $fbApi = FacebookAds\Api::init(self::APP_ID, self::APP_SECRET, $accessToken);
     $fbApi->setLogger(new FacebookLoggerWrapper($this->get('logger')));
     $me = new AdUser('me');
     $adAccount = $me->getAdAccounts()->current();
     $adAccountId = $adAccount->getData()[AdFields::ACCOUNT_ID];
     $client = $this->createHttpClient();
     return new AdApi($adAccountId, self::PAGE_ID, $accessToken, $client);
 }
 /**
  * @param Api|null $instance
  * @return Api
  * @throws \InvalidArgumentException
  */
 protected static function assureApi(Api $instance = null)
 {
     $instance = $instance ?: Api::instance();
     if (!$instance) {
         throw new \InvalidArgumentException('An Api instance must be provided as argument or ' . 'set as instance in the \\FacebookAds\\Api');
     }
     return $instance;
 }
Пример #13
0
 protected function setupApi()
 {
     $this->api = new Api($this->getHttpClient(), $this->getSession());
     $this->api->setLogger($this->getLogger());
     Api::setInstance($this->api);
 }
// _DOC close [CUSTOM_AUDIENCE_DELETE]
$api = Api::instance();
$response = $api->call('/me/accounts');
$data = $response->getContent();
$page_token = '';
foreach ($data['data'] as $page) {
    if ($page['id'] == $page_id) {
        $page_token = $page['access_token'];
        break;
    }
}
if ($page_token === '') {
    throw new \InvalidArgumentException('Page access token for the page id ' . $page_id . ' cannot be found.');
}
$page_session = new Session($config->appId, $config->appSecret, $page_token);
$page_api = new Api($api->getHttpClient(), $page_session);
$page_api->setLogger($api->getLogger());
$request = $page_api->prepareRequest('/' . $page_id . '/videos', RequestInterface::METHOD_POST);
$request->setLastLevelDomain('graph-video');
$request->getFileParams()->offsetSet('source', $video_path);
$response = $page_api->executeRequest($request);
$data = $response->getContent();
$video_id = is_string($data) ? $data : (string) $data['id'];
// _DOC open [CUSTOM_AUDIENCE_CREATE_VIDEO_VIEWS_RETARGET]
// _DOC vars [ad_account_id:s, video_id]
// use FacebookAds\Object\CustomAudience;
// use FacebookAds\Object\Fields\CustomAudienceFields;
// use FacebookAds\Object\Values\CustomAudienceSubtypes;
$lookalike = new CustomAudience(null, $ad_account_id);
$lookalike->setData(array(CustomAudienceFields::SUBTYPE => CustomAudienceSubtypes::LOOKALIKE, CustomAudienceFields::LOOKALIKE_SPEC => array('ratio' => 0.01, 'country' => 'US', 'engagement_specs' => array(array('action.type' => 'video_view', 'post' => $video_id)), 'conversion_type' => 'dynamic_rule')));
$lookalike->create();
Пример #15
0
 public function testBase64UrlEncode()
 {
     $this->assertEquals('MTIzNDU', Api::base64UrlEncode('12345'));
 }
Пример #16
0
 // Logged in!
 $_SESSION['facebook_access_token'] = (string) $accessToken;
 $short_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($short_access_token);
 // Sets the default fallback access token so we don't have to pass it to each request
 $fb->setDefaultAccessToken($longLivedAccessToken);
 try {
     $response = $fb->get('/me');
     $userNode = $response->getGraphUser();
     // Add to header of your file
     // Add after echo "You are logged in "
     // Initialize a new Session and instantiate an Api object
     Api::init($CLIENT_ID, $APP_SECRET, $longLivedAccessToken);
     // Add after Api::init()
     $me = new AdUser('me');
     $my_adaccount = $me->getAdAccounts()->current();
     print_r($my_adaccount->getData());
     // $page_token = $fb -> get("/$PAGE_ID") ->getAccessToken() ;
     // $albums = $fb -> get("/$PAGE_ID/albums") -> getGraphEdge();
     // $photo = $fb -> post("$ALBUM_ID/photos", array( 'source' => $fb ->fileToUpload("Monkey.D..Luffy.full.476449.jpg"), "message" => 'New photo hello' ), $page_token);
     // $total_post = $fb -> get("/$PAGE_ID/feed") -> getGraphEdge() ->asJson();
     //			echo $total_post;
     /* PHP SDK v5.0.0 */
     /* make the API call */
 } catch (Facebook\Exceptions\FacebookResponseException $e) {
     // When Graph returns an error
     echo 'Graph returned an error: ' . $e->getMessage();
     exit;
<?php

require './vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Values\InsightsPresets;
use FacebookAds\Object\Values\InsightsLevels;
function requireEnv($key)
{
    $value = getenv($key);
    if (!$value) {
        throw new \InvalidArgumentException(sprintf('Environment variable %s must be set', $key));
    }
    return $value;
}
Api::init(requireEnv('FACEBOOK_APP_ID'), requireEnv('FACEBOOK_APPSECRET'), requireEnv('FACEBOOK_ACCESS_TOKEN'));
function waitForJobToComplete($job)
{
    sleep(2);
    $job->read();
    while (!$job->isComplete()) {
        sleep(5);
        $job->read();
    }
    $cursor = $job->getResult();
    $cursor->setUseImplicitFetch(true);
    return $cursor;
}
function queryTotal(array $dimensions, $column, \DateTime $date)
{
    $account = new AdAccount(requireEnv('FACEBOOK_ACCOUNT_ID'));
<?php

// Add to header of your file
require_once __DIR__ . '/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\AdUser;
use FacebookAds\Logger\CurlLogger;
session_start();
$cwd = getcwd();
$conf = json_decode(file_get_contents("{$cwd}/conf/conf.json"), true);
$access_token = isset($_SESSION['facebook_access_token']) ? $_SESSION['facebook_access_token'] : $conf['access_token'];
print_r("<PRE>");
Api::init($conf['app_id'], $conf['app_secret'], $_SESSION['facebook_access_token']);
$me = new AdUser('me');
$my_adaccount = $me->getAdAccounts()->current();
print_r($my_adaccount->getData());
print_r("</PRE>");
 /**
  * Authenticate & initiate
  *
  * @param string $appId
  * @param string $appSecret
  * @param string $token
  * @return Api|null
  */
 public function instanceWithAuth($appId, $appSecret, $token)
 {
     Api::init($appId, $appSecret, $token);
     return Api::instance();
 }
$access_token = null;
$app_id = null;
$app_secret = null;
// should begin with "act_" (eg: $account_id = 'act_1234567890';)
$account_id = null;
define('SDK_DIR', __DIR__ . '/..');
// Path to the SDK directory
$loader = (include SDK_DIR . '/vendor/autoload.php');
// Configurations - End
if (is_null($access_token) || is_null($app_id) || is_null($app_secret)) {
    throw new \Exception('You must set your access token, app id and app secret before executing');
}
if (is_null($account_id)) {
    throw new \Exception('You must set your account id before executing');
}
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
Api::init($app_id, $app_secret, $access_token);
// Create the CurlLogger
$logger = new CurlLogger();
// To write to a file pass in a file handler
// $logger = new CurlLogger(fopen('test','w'));
// If you need to escape double quotes, use the following - useful for docs
$logger->setEscapeLevels(1);
// Hide target ids and tokens
$logger->setShowSensitiveData(false);
// Attach the logger to the Api instance
Api::instance()->setLogger($logger);
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
$account = (new AdAccount($account_id))->read(array(AdAccountFields::ID, AdAccountFields::NAME, AdAccountFields::ACCOUNT_STATUS));
Пример #21
0
use FacebookAds\Object\AdAccount;
use FacebookAds\Logger\CurlLogger;
use FacebookAdsTest\Bootstrap;
$relative_path = getcwd();
chdir(__DIR__);
if (!ini_get('date.timezone')) {
    ini_set('date.timezone', 'UTC');
}
$loader = (require __DIR__ . '/../autoload.php');
require_once __DIR__ . '/../../test/FacebookAdsTest/Bootstrap.php';
// Setup the same env as our tests
Bootstrap::initAutoloader();
$config = Bootstrap::initIntegrationConfig();
Api::init($config->appId, $config->appSecret, $config->accessToken);
if (in_array('--dump', $_SERVER['argv'])) {
    Api::instance()->setLogger(new CurlLogger(STDERR));
}
$get_class_name = function ($object) {
    return (new ReflectionClass($object))->getShortName();
};
$delete_object = function (AbstractCrudObject $object) use($get_class_name) {
    echo sprintf(' > Deleting %s %d', $get_class_name($object), $object->{AbstractCrudObject::FIELD_ID}) . PHP_EOL;
    $object->delete();
};
$clean_edge = function ($cursor_provider) use($get_class_name, $delete_object) {
    try {
        $cursor = call_user_func($cursor_provider);
        if (!$cursor instanceof Cursor) {
            throw new ErrorException(sprintf("Provider returned instance of %s", $get_class_name($cursor)));
        }
        $cursor->setUseImplicitFetch(true);
 /**
  * @param $userId
  *
  * @return FacebookAdsAuthContainer
  */
 public function getAuthContainer($userId)
 {
     $oauthTokens = $this->MediaPlatformUser->getOauthTokens($userId);
     if (empty($oauthTokens)) {
         throw new NotFoundException('Could not find the oauth tokens for MediaPlatformUser #' . $userId . '.');
     }
     $facebookAuthContainer = new FacebookAdsAuthContainer();
     $this->_facebook->setDefaultAccessToken($oauthTokens['OauthToken']['access_token']);
     $facebookAuthContainer->facebookSdk = $this->_facebook;
     $facebookAuthContainer->facebookAds = Api::init(Configure::read('FacebookAds.app_id'), Configure::read('FacebookAds.app_secret'), $oauthTokens['OauthToken']['access_token']);
     $this->_sendEventIfTokenExpiresInTwoWeeks($userId, $oauthTokens['OauthToken']['token_expires']);
     return $facebookAuthContainer;
 }
 /**
  * @param string $retailer_id
  * @param int $catalog_id
  * @return string
  */
 public static function buildCatalogUrlForRetailerId($retailer_id, $catalog_id)
 {
     return '/catalog:' . $catalog_id . ':' . Api::base64UrlEncode($retailer_id);
 }
 /**
  * {@inheritdoc}
  */
 public function init($accessToken)
 {
     Api::init(config('facebook-ads.app_id'), config('facebook-ads.app_secret'), $accessToken);
     return Api::instance();
 }
Пример #25
0
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */
use FacebookAds\Bootstrap;
use FacebookAds\Api;
chdir(__DIR__);
if (!ini_get('date.timezone')) {
    ini_set('date.timezone', 'UTC');
}
// FIXME - @pruno
// Untill we will run in full CI mode, composer won't be here, autoload manually
require_once __DIR__ . '/../src/SplClassLoader.php';
(new SplClassLoader('FacebookAds', __DIR__ . '/../../src/'))->register();
echo sprintf('v%s', Api::init('', '', '')->getDefaultGraphVersion()) . PHP_EOL;
Пример #26
0
 public function testNullableLogger()
 {
     $api = new Api($this->getSession(), null);
     $this->assertTrue($api->getLogger() instanceof NullLogger);
 }
$app_id = null;
$app_secret = null;
// should begin with "act_" (eg: $account_id = 'act_1234567890';)
$account_id = null;
// Configurations - End
if (is_null($access_token) || is_null($app_id) || is_null($app_secret)) {
    throw new \Exception('You must set your access token, app id and app secret before executing');
}
if (is_null($account_id)) {
    throw new \Exception('You must set your account id before executing');
}
define('SDK_DIR', __DIR__ . '/..');
// Path to the SDK directory
$loader = (include SDK_DIR . '/vendor/autoload.php');
use FacebookAds\Api;
Api::init($app_id, $app_secret, $access_token);
// use the namespace for Custom Audiences and Fields
use FacebookAds\Object\CustomAudience;
use FacebookAds\Object\Fields\CustomAudienceFields;
use FacebookAds\Object\Values\CustomAudienceTypes;
// Create a custom audience object, setting the parent to be the account id
$audience = new CustomAudience(null, $account_id);
$audience->setData(array(CustomAudienceFields::NAME => 'My Custom Audiece', CustomAudienceFields::DESCRIPTION => 'Lots of people'));
// Create the audience
$audience->create();
echo "Audience ID: " . $audience->id . "\n";
// Assuming you have an array of emails:
// NOTE: The SDK will hash (SHA-2) your data before submitting
// it to Facebook servers
$emails = array('*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**');
$audience->addUsers($emails, CustomAudienceTypes::EMAIL);
Пример #28
0
$business_id = $config->businessId;
$api = Api::instance();
$response = $api->call('/me/accounts');
$data = $response->getContent();
$page_token = '';
foreach ($data['data'] as $page) {
    if ($page['id'] == $page_id) {
        $page_token = $page['access_token'];
        break;
    }
}
if ($page_token === '') {
    throw new \InvalidArgumentException('Page access token for the page id ' . $page_id . ' cannot be found.');
}
$page_session = new Session($config->appId, $config->appSecret, $page_token);
$page_api = new Api($api->getHttpClient(), $page_session);
$page_api->setLogger($api->getLogger());
$data = $page_api->call('/' . $page_id . '/promotable_posts', RequestInterface::METHOD_GET)->getContent();
if (is_null($data) || !is_array($data['data']) || count($data['data']) === 0) {
    throw new \RuntimeException("no promotable posts available for page " . $page_id);
}
$post_id = $data['data'][0]['id'];
// create Ad Image
$zip_path = $config->testZippedImagesPath;
$images = AdImage::createFromZip($zip_path, $ad_account_id);
$image_1_hash = $images[0]->{AdImageFields::HASH};
$image_2_hash = $images[1]->{AdImageFields::HASH};
$image_3_hash = $images[1]->{AdImageFields::HASH};
// create Ad Video
$retry_delay = 3;
$max_retry = 4;