My code:
// Set your access token here:
$access_token = "XXX";
$app_id = "XXX";
$app_secret = "XXX";
// should begin with "act_" (eg: $account_id = 'act_1234567890';)
$account_id = "XXX";
$page_id = "XXX";
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 FacebookAds\Object\AdCreative;
use FacebookAds\Object\Fields\AdCreativeFields;
use FacebookAds\Object\ObjectStorySpec;
use FacebookAds\Object\Fields\ObjectStorySpecFields;
use FacebookAds\Object\ObjectStory\LinkData;
use FacebookAds\Object\Fields\ObjectStory\LinkDataFields;
use FacebookAds\Object\ObjectStory\AttachmentData;
use FacebookAds\Object\Fields\ObjectStory\AttachmentDataFields;
use FacebookAds\Object\AdGroup;
use FacebookAds\Object\Fields\AdGroupFields;
// Create a new AdCreative
$creative = new AdCreative(null, $account_id);
$creative->{AdCreativeFields::NAME} = 'Multi Product Ad Creative';
// Create a new ObjectStorySpec to create an unpublished post
$story = new ObjectStorySpec();
$story->{ObjectStorySpecFields::PAGE_ID} = $page_id;
// Create LinkData object representing data for a link page post
$link = new LinkData();
$link->{LinkDataFields::LINK} = 'http://www.example.com/products';
$link->{LinkDataFields::CAPTION} = 'WWW.EXAMPLE.COM';
// Create 3 products as this will be a multi-product ad
$product1 = (new AttachmentData())->setData(array(
AttachmentDataFields::LINK => 'http://www.example.com/p1',
AttachmentDataFields::IMAGE_HASH => '<AD_IMAGE_HASH_1>',
AttachmentDataFields::NAME => 'Product 1',
AttachmentDataFields::DESCRIPTION => '$4.99',
));
$product2 = (new AttachmentData())->setData(array(
AttachmentDataFields::LINK => 'http://www.example.com/p2',
AttachmentDataFields::IMAGE_HASH => '<AD_IMAGE_HASH_2>',
AttachmentDataFields::NAME => 'Product 2',
AttachmentDataFields::DESCRIPTION => '$10.99',
));
$product3 = (new AttachmentData())->setData(array(
AttachmentDataFields::LINK => 'http://www.example.com/p3',
AttachmentDataFields::IMAGE_HASH => '<AD_IMAGE_HASH_3>',
AttachmentDataFields::NAME => 'Product 3',
AttachmentDataFields::DESCRIPTION => '$29.99',
));
// Add the products into the child attachments
$link->{LinkDataFields::CHILD_ATTACHMENTS} = array(
$product1,
$product2,
$product3,
);
$story->{ObjectStorySpecFields::LINK_DATA} = $link;
$creative->{AdCreativeFields::OBJECT_STORY_SPEC} = $story;
$creative->create();
The exception:
Fatal error: Uncaught exception 'FacebookAds\Http\Exception\ServerException' with message 'Service temporarily unavailable' in C:\xampp\htdocs\fbtool\facebook-php-ads-sdk-master\src\FacebookAds\Http\Exception\RequestException.php:140 Stack trace: #0 C:\xampp\htdocs\fbtool\facebook-php-ads-sdk-master\src\FacebookAds\Http\Client.php(216): FacebookAds\Http\Exception\RequestException::create(Array, 500) #1 C:\xampp\htdocs\fbtool\facebook-php-ads-sdk-master\src\FacebookAds\Http\Request.php(276): FacebookAds\Http\Client->sendRequest(Object(FacebookAds\Http\Request)) #2 C:\xampp\htdocs\fbtool\facebook-php-ads-sdk-master\src\FacebookAds\Api.php(140): FacebookAds\Http\Request->execute() #3 C:\xampp\htdocs\fbtool\facebook-php-ads-sdk-master\src\FacebookAds\Api.php(182): FacebookAds\Api->executeRequest(Object(FacebookAds\Http\Request)) #4 C:\xampp\htdocs\fbtool\facebook-php-ads-sdk-master\src\FacebookAds\Object\AbstractCrudObject.php(248): FacebookAds\Api->call('/act_XXX/...', 'POST', Array) #5 C:\xampp\htdocs\fbtool\facebook- in C:\xampp\htdocs\fbtool\facebook-php-ads-sdk-master\src\FacebookAds\Http\Exception\RequestException.php on line 140
If I change the access token or something the server responses the correct error. So I think the service is not really unavailable.
Related
I have implemented google sign-in for my web app, in which I've used this library: https://metacpan.org/pod/Google::RestApi::Auth::OAuth2Client to get the code value, the access token and after that the user's information (email, name, google-id).
My problem in this implementation is that the user is prompt for consent where he needs to insert his information (email and password) and I would like to redirect the user for consent where he is able to select the accounts, and not insert his information. I don't know if my implementation, where I make the GET request, is incorrect or if it is because of the library that I use.
In front-end, I have a form which calls a route that redirects to my back-end function 'on_google_login':
sub on_google_login {
my $self = shift;
my $redirect_name = $self->get_redirect_name();
$self->session(redirect => $redirect_name);
my $google = Google::RestApi::Auth::OAuth2Client->new(
client_id => $ENV{GOOGLE_CLIENT_ID},
client_secret => $ENV{GOOGLE_SECRET},
redirect_uri => $ENV{GOOGLE_BASE_URL} . '/google_callback'
);
my $url = $google->authorize_url(
display => 'page'
);
$self->redirect_to($url);
}
And this is my callback function, where I extract the 'code' and I request the user's information using the access token.
sub on_google_callback {
my $self = shift;
my $code = $self->req->param('code');
my $google = Google::RestApi::Auth::OAuth2Client->new(
client_id => $ENV{GOOGLE_CLIENT_ID},
client_secret => $ENV{GOOGLE_SECRET},
redirect_uri => $ENV{GOOGLE_BASE_URL} . '/google_callback'
);
if (not (defined $code)) {
return $self->render(text => 'Did not connect to Google');
}
my $redirect_name = $self->session('redirect') // 'home';
delete $self->session->{'redirect'};
my $access_token = $google->access_token($code)->access_token;
my $url = $ENV{GOOGLE_ENDPOINT} . $access_token;
my $request = HTTP::Request->new(GET => $url);
my $ua = LWP::UserAgent->new();
my $info = decode_json($ua->request($request)->content);
my ($google_id, $name, $mail) = ($info->{sub}, $info->{name}, $info->{email});
if (!defined $google_id) {
return $self->render(
template => 'validation/custom_error',
title => 'Error logging in with Google',
message => 'Sorry, something went wrong when attempting to log you in ' .
'with Google. Please try again and contact us in the chat if this ' .
'persists.',
status => 400);
}
my $found_user = $self->db->resultset('User')->by_mail($mail);
if ($found_user) {
return unless validate_user_can_login($self, $found_user);
return unless set_user_data_on_login($self, $found_user);
$self->redirect_to($redirect_name);
} else {
$self->session(name => $name);
$self->session(mail => $mail);
$self->redirect_to('/register');
}
return;
}
Hi Guys first of all let me tell you guys that I am a newbie with CakePHP and MVC also but one of my old client requested me some favor which I took as a challenge. So If anyone can help me I will appreciate a lot.
I have a CakePHP 2.9 application where OAuth is not working properly following is the code for app/Controller/UsersController.php
public function facebookLogin(){
$this->layout = false;
App::import('Vendor', 'Facebook/facebook');
/*$facebook = new Facebook(array(
'appId' => '1867587306812489', // Facebook App ID
'secret' => '9fb41a07d3da3406dbab5861c3498764', // Facebook App Secret
'cookie' => false,
)
); */
$facebook = new Facebook(array(
'appId' => '1887387108164606', // Facebook App ID
'secret' => '8d733aa6a4501ce27fde9626429baab9', // Facebook App Secret
'cookie' => false,
)
);
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me?fields=first_name,last_name,email');
$usersArr = $this->User->find('first',array('conditions'=>array('User.email'=>$user_profile['email'],'User.social_id'=>$user_profile['id'],'User.role_id'=>0)));
$user_count = $this->User->find('first',array('conditions'=>array(),'order'=>'User.id DESC','limit'=>1));
if(empty($usersArr)){
$saveUserArr['User']['username'] = trim($user_profile['first_name']).' '.trim($user_profile['last_name']);
$saveUserArr['User']['firstname'] = $user_profile['first_name'];
$saveUserArr['User']['lastname'] = $user_profile['last_name'];
/* $user_n = $saveUserArr['User']['first_name'].'.'.$saveUserArr['User']['last_name'];
$user_cnt = $user_count['User']['id'] + 1;
$user_n = str_replace(' ','_',$user_n).'.'.$user_cnt;
$saveUserArr['User']['user_unique_id'] = $user_n; */
$saveUserArr['User']['email'] = $user_profile['email'];
$saveUserArr['User']['password'] = '123456';
$saveUserArr['User']['social_id'] = $user_profile['id'];
$saveUserArr['User']['login_from'] = 'facebook';
$saveUserArr['User']['role_id'] = 0;
$this->User->save($saveUserArr['User'],false);
}else{
$this->User->id = $usersArr['User']['id'];
$this->User->saveField('social_id', $user_profile['id']);
$this->User->saveField('login_from', 'facebook');
}
$this->request->data['User']['email'] = $user_profile['email'];
$this->request->data['User']['login_from'] = 'facebook';
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email', // Permissions to request from the user
));
return $this->redirect($loginUrl);
}
}
private function deleteFacebookSession(){
Configure::write('debug', 0);
if(!$this->Session->check('Auth.User')){
foreach( $this->Session->read() as $key => $value ) {
if( strpos( $key, 'fb_' ) === 0 ) {
$this->Session->delete($key);
}
}
}
}
It throws following error:
The oauth script url is not properly configured in your fb app.
You may go to your fb app settings and look for APP DOMAIN.
Include your domain there:
If you are developing in your localhost, you may want to create a server.local rec in your hosts file so you can access your localserver as server.local.
Also, you can create test versions of the main fb app, and allows you to have a copy of your fb app that works in other environments, it is called "create test app"
I receive an erro of Invalid parameter but it doesnt tell me which invalid parameter is. The error is:
Fatal error: Uncaught exception
'FacebookAds\Http\Exception\AuthorizationException' with message
'Invalid parameter' in
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Exception\RequestException.php:140
Stack trace: #0
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Client.php(215):
FacebookAds\Http\Exception\RequestException::create(Object(FacebookAds\Http\Response))
1 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Request.php(282):
FacebookAds\Http\Client->sendRequest(Object(FacebookAds\Http\Request))
2 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Api.php(151):
FacebookAds\Http\Request->execute() #3
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Api.php(193):
FacebookAds\Api->executeRequest(Object(FacebookAds\Http\Request)) #4
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Object\AbstractCrudObject.php(208):
FacebookAds\Api->call('/act_XXXXXXXX...', 'POST', Array) #5 C:\A in
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Exception\RequestException.php
on line 140
This is my code and it seems that the error is in the last object $ad = new Ad, everything is created fine until the Ad, it shows me this error.
<?php
//date_default_timezone_set('America/Lima');
//require_once('vendor/autoload.php');
//$campaign_id = '6053849657204';
// Configurations
$access_token = 'MYTOKEN';
$app_id = 'MYAPPID';
$app_secret = 'MYAPPSECRET';
$account_id = 'act_MYACCOUNT';
define('SDK_DIR', __DIR__ . ''); // Path to the SDK directory
$loader = include SDK_DIR.'/vendor/autoload.php';
date_default_timezone_set('America/Los_Angeles');
// 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;
Api::init($app_id, $app_secret, $access_token);
/**
* Step 1 Read the AdAccount (optional)
*/
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
$account = (new AdAccount($account_id))->read(array(
AdAccountFields::ID,
AdAccountFields::NAME,
AdAccountFields::ACCOUNT_STATUS,
));
echo "\nUsing this account: ";
echo $account->id."\n";
// Check the account is active
if($account->{AdAccountFields::ACCOUNT_STATUS} !== 1) {
throw new \Exception(
'This account is not active');
}
/**
* Step 2 Create the Campaign
*/
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Values\AdObjectives;
$campaign = new Campaign(null, $account->id);
$campaign->setData(array(
CampaignFields::NAME => 'Noticia 1',
CampaignFields::OBJECTIVE => AdObjectives::LINK_CLICKS,
));
$campaign->validate()->create(array(
Campaign::STATUS_PARAM_NAME => Campaign::STATUS_PAUSED,
));
echo "Campaign ID:" . $campaign->id . "\n";
/**
* Step 3 Search Targeting
*/
use FacebookAds\Object\TargetingSearch;
use FacebookAds\Object\Search\TargetingSearchTypes;
use FacebookAds\Object\TargetingSpecs;
use FacebookAds\Object\Fields\TargetingSpecsFields;
$results = TargetingSearch::search(
$type = TargetingSearchTypes::INTEREST,
$class = null,
$query = 'facebook');
// we'll take the top result for now
$target = (count($results)) ? $results->current() : null;
echo "Using target: ".$target->name."\n";
$targeting = new TargetingSpecs();
$targeting->{TargetingSpecsFields::GEO_LOCATIONS}
= array('countries' => array('PE'));
/*$targeting->{TargetingSpecsFields::INTERESTS} = array(
array(
'id' => $target->id,
'name' => $target->name,
),
);*/
/**
* Step 4 Create the AdSet
*/
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Values\OptimizationGoals;
use FacebookAds\Object\Values\BillingEvents;
$adset = new AdSet(null, $account->id);
$adset->setData(array(
AdSetFields::NAME => 'Latam 1',
AdSetFields::CAMPAIGN_ID => $campaign->id,
AdSetFields::DAILY_BUDGET => '150',
AdSetFields::TARGETING => $targeting,
AdSetFields::OPTIMIZATION_GOAL => OptimizationGoals::REACH,
AdSetFields::BILLING_EVENT => BillingEvents::IMPRESSIONS,
AdSetFields::BID_AMOUNT => '1',
AdSetFields::START_TIME =>
(new \DateTime("+1 week"))->format(\DateTime::ISO8601),
AdSetFields::END_TIME =>
(new \DateTime("+2 week"))->format(\DateTime::ISO8601),
));
$adset->validate()->create(array(
AdSet::STATUS_PARAM_NAME => AdSet::STATUS_ACTIVE,
));
echo 'AdSet ID: '. $adset->id . "\n";
/**
* Step 5 Create an AdImage
*/
use FacebookAds\Object\AdImage;
use FacebookAds\Object\Fields\AdImageFields;
$image = new AdImage(null, $account->id);
$image->{AdImageFields::FILENAME}
= dirname(__FILE__).'/image.jpg';
$image->create();
echo 'Image Hash: '.$image->hash . "\n";
/**
* Step 6 Create an AdCreative
*/
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\AdCreativeObjectStorySpec;
use FacebookAds\Object\Fields\AdCreativeObjectStorySpecFields;
use FacebookAds\Object\Fields\AdCreativeFields;
$link_data = new AdCreativeLinkData();
$link_data->setData(array(
AdCreativeLinkDataFields::MESSAGE => 'MY DESC',
AdCreativeLinkDataFields::LINK => 'MY WEB',
AdCreativeLinkDataFields::CAPTION => 'My caption',
AdCreativeLinkDataFields::IMAGE_HASH => $image->hash,
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => 'MY PAGE ID',
AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));
$creative = new AdCreative(null, $account->id);
$creative->setData(array(
AdCreativeFields::NAME => 'Sample Creative',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
$creative->create();
echo 'Creative ID: '.$creative->id . "\n";
/**
* Step 7 Create an Ad
*/
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;
$datax = array(
AdFields::NAME => 'My Ad',
AdFields::ADSET_ID => $adset->id,
AdFields::CREATIVE => array(
'creative_id' => $creative->id,
),
);
$ad = new Ad(null, $account->id);
$ad->setData($datax);
$ad->create(array(
Ad::STATUS_PARAM_NAME => Ad::STATUS_PAUSED,
));
echo 'Ad ID:' . $ad->id . "\n";
The issue was that you needed to specify a valid Link and Page ID. I figured that out by adding more logging in the code below by adding this piece of code,
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'));
// Attach the logger to the Api instance
Api::instance()->setLogger($logger);
Once you've added the above code to your php project, it will console output the curl version of the API calls being executed by the SDK. You can make the API call that was failing in a terminal using curl and get the specific error that the API throws for debugging. (Currently in the PHP SDK the exact error doesn't get propagated up in the exceptions.)
You can check out the complete working code snippet here,
<?php
$access_token = '<ACCESS_TOKEN>';
$app_id = <APP_ID>;
$app_secret = '<APP_SECRET>';
// should begin with "act_" (eg: $account_id = 'act_1234567890';)
$account_id = 'act_<ACCOUNT_ID>';
$page_id = 0; // REPLACE THIS WITH VALID PAGE ID.
// 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;
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'));
// Attach the logger to the Api instance
Api::instance()->setLogger($logger);
/**
* Step 1 Read the AdAccount (optional)
*/
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
$account = (new AdAccount($account_id))->read(array(
AdAccountFields::ID,
AdAccountFields::NAME,
AdAccountFields::ACCOUNT_STATUS,
));
echo "\nUsing this account: ";
echo $account->id."\n";
// Check the account is active
if($account->{AdAccountFields::ACCOUNT_STATUS} !== 1) {
throw new \Exception(
'This account is not active');
}
/**
* Step 2 Create the Campaign
*/
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Values\AdObjectives;
$campaign = new Campaign(null, $account->id);
$campaign->setData(array(
CampaignFields::NAME => 'Noticia 1',
CampaignFields::OBJECTIVE => AdObjectives::LINK_CLICKS,
));
$campaign->validate()->create(array(
Campaign::STATUS_PARAM_NAME => Campaign::STATUS_PAUSED,
));
echo "Campaign ID:" . $campaign->id . "\n";
/**
* Step 3 Search Targeting
*/
use FacebookAds\Object\TargetingSearch;
use FacebookAds\Object\Search\TargetingSearchTypes;
use FacebookAds\Object\TargetingSpecs;
use FacebookAds\Object\Fields\TargetingSpecsFields;
$results = TargetingSearch::search(
$type = TargetingSearchTypes::INTEREST,
$class = null,
$query = 'facebook');
// we'll take the top result for now
$target = (count($results)) ? $results->current() : null;
echo "Using target: ".$target->name."\n";
$targeting = new TargetingSpecs();
$targeting->{TargetingSpecsFields::GEO_LOCATIONS}
= array('countries' => array('PE'));
/*$targeting->{TargetingSpecsFields::INTERESTS} = array(
array(
'id' => $target->id,
'name' => $target->name,
),
);*/
/**
* Step 4 Create the AdSet
*/
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Values\OptimizationGoals;
use FacebookAds\Object\Values\BillingEvents;
$adset = new AdSet(null, $account->id);
$adset->setData(array(
AdSetFields::NAME => 'Latam 1',
AdSetFields::CAMPAIGN_ID => $campaign->id,
AdSetFields::DAILY_BUDGET => '150',
AdSetFields::TARGETING => $targeting,
AdSetFields::OPTIMIZATION_GOAL => OptimizationGoals::REACH,
AdSetFields::BILLING_EVENT => BillingEvents::IMPRESSIONS,
AdSetFields::BID_AMOUNT => '1',
AdSetFields::START_TIME =>
(new \DateTime("+1 week"))->format(\DateTime::ISO8601),
AdSetFields::END_TIME =>
(new \DateTime("+2 week"))->format(\DateTime::ISO8601),
));
$adset->validate()->create(array(
AdSet::STATUS_PARAM_NAME => AdSet::STATUS_ACTIVE,
));
echo 'AdSet ID: '. $adset->id . "\n";
/**
* Step 5 Create an AdImage
*/
use FacebookAds\Object\AdImage;
use FacebookAds\Object\Fields\AdImageFields;
$image = new AdImage(null, $account->id);
$image->{AdImageFields::FILENAME}
= dirname(__FILE__).'/image.jpg';
$image->create();
echo 'Image Hash: '.$image->hash . "\n";
/**
* Step 6 Create an AdCreative
*/
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\AdCreativeObjectStorySpec;
use FacebookAds\Object\Fields\AdCreativeObjectStorySpecFields;
use FacebookAds\Object\Fields\AdCreativeFields;
$link_data = new AdCreativeLinkData();
$link_data->setData(array(
AdCreativeLinkDataFields::MESSAGE => 'MY DESC',
AdCreativeLinkDataFields::LINK => 'www.google.com',
AdCreativeLinkDataFields::CAPTION => 'My caption',
AdCreativeLinkDataFields::IMAGE_HASH => $image->hash,
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => $page_id,
AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));
$creative = new AdCreative(null, $account->id);
$creative->setData(array(
AdCreativeFields::NAME => 'Sample Creative',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
$creative->create();
echo 'Creative ID: '.$creative->id . "\n";
/**
* Step 7 Create an Ad
*/
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;
$datax = array(
AdFields::NAME => 'My Ad',
AdFields::ADSET_ID => $adset->id,
AdFields::CREATIVE => array(
'creative_id' => $creative->id,
),
);
$ad = new Ad(null, $account->id);
$ad->setData($datax);
$ad->create(array(
Ad::STATUS_PARAM_NAME => Ad::STATUS_PAUSED,
));
echo 'Ad ID:' . $ad->id . "\n";
I've used the following code. It works fine without 'scheduled_publish_time', otherwise I get this error "(#100) You cannot specify a scheduled publish time on a published post".
I've previously registered my app with another piece of code. It's so weird.
include_once("inc/facebook.php"); //include facebook SDK
$appId = '21xxxxxxxxxxx'; //Facebook App ID
$appSecret = '6b8f4bxxxxxxxxxxxxxd56'; // Facebook App Secret
$return_url = 'http://localhost:8888/...'; //return url (url to script)
$homeurl = 'http://localhost:8888/...'; //return to home
$fbPermissions = 'publish_stream,manage_pages'; //Required facebook permissions
//Call Facebook API
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
'cookie' => true,
'fileUpload' => true
));
$accounts = $facebook->api('/me/accounts');
$PAGE_ID = get_option('fb_post_cron_page'); // it is an option saved in WordPress
foreach($accounts['data'] as $account){
if($account['id'] == $PAGE_ID){
$ACCESS_TOKEN = $account['access_token'];
}
}
$post_url = '/'.$PAGE_ID.'/photos';
$upload_dir = wp_upload_dir();
$upload_dir= $upload_dir['path'];
$timezone= 'Europe/Rome';
$date = new DateTime($dateStr, new DateTimeZone($timezone));
//posts message on page statues
$args = array(
'access_token' => $ACCESS_TOKEN,
'source' => '#' . $image_abs_path,
'message' => $post_message,
'published' => true,
'scheduled_publish_time' => $date->getTimestamp()
);
try {
$postResult = $facebook->api($post_url, 'post', $args );
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
you have to set 'published' to false
$args = array(
'access_token' => $ACCESS_TOKEN,
'source' => '#' . $image_abs_path,
'message' => $post_message,
'published' => false,
'scheduled_publish_time' => $date->getTimestamp()
);
I'm using the Facebook Graph API and want to check if a user has authenticated my Facebook app by user ID. How do I do this?
You use:
SELECT is_app_user FROM user WHERE uid=USER_ID
This should return:
[
{
"is_app_user": true
}
]
If the user has logged in to your application.
Expanding on ifaour's answer, in PHP this query would look something like this:
<?php
$facebook = new Facebook(
'appID' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET
);
$result = $facebook->api(array(
'method' => 'fql.query',
'query' => "SELECT is_app_user FROM user WHERE uid=$user_id"
));
$is_installed = $result[0]['is_app_user'];
Here you can batch multiple requests together and avoid using FQL.
Assuming you have already logged into facebook and set the access token to the application access token, you can do this:
$batch = array();
foreach($friendArray AS $friend) {
$batch[] = array(
'method' => 'GET',
'relative_url' => '/' . $friend . '?fields=installed'
);
}
FB()->useApplicationAccessToken();
$batchResponse = FB()->facebook()->api('?batch='.json_encode($batch), 'POST');
Then you can process the batch response with code like this:
$installedUsers = array();
$notInstalledUsers = array();
foreach ($batchResponse AS $response) {
$body = json_decode($response['body'], true);
if (!isset($body['id']))
continue;
$id = $body['id'];
if (isset($body['installed']))
$installedUsers[] = $id;
else
$notInstalledUsers[] = $id;
}