How to setup a Facebook API session - php

I am exploring the Facebook API for a couple of days now, because I am trying to get leads from my Facebook page using Webhooks with Lead Ads.
After reading a bunch of articles and Facebook documentation I noticed that for a lot functions in the documentation you see a $session variable defined (for example here and here).
Because I want to get the leads from my Facebook page I started following this article, which explains how to get real time lead updates from Facebook.
The article starts with setting up a request for receiving the app subscriptions for your Facebook page. But I directly came into trouble with creating the session, because it looks like the FacebookSession class does not exists in the current Facebook SDK anymore.
How do I need to setup this session? Because I can not find anywhere in the SDK files the FacebookSession class, so I think in the mean time this is changed.
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
// I cannot find this class anywhere
$session = new FacebookSession('<APP_ACCESS_TOKEN>');
$request = new FacebookRequest(
$session,
'POST',
'/<APP_ID>/subscriptions',
array(
'object' => 'page',
'callback_url' => '<YOUR_CALLBACK_URL>',
'fields' => 'conversations',
'verify_token' => '<YOUR_VERIFY_TOKEN>',
)
);
$response = $request->execute();
I get an 500 server error with the following message:
Fatal error: Class 'Facebook\FacebookSession' not found in ...

Related

Facebook Marketing API PHP SDK - "Filtering field delivery_info is invalid"

I'm attempting to make a PHP-application that generates Facebook ad reports for a company, using the Facebook PHP Ads SDK. I'm following the Marketing API QuickStart that essentially generates code for you. I have all access I need to reach the company's ad account ID.
(I'm not showing the token- and ID-variables, unless absolutely necessary. If so, tell me).
require __DIR__ . '/vendor/autoload.php';
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\AdsInsights;
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
$access_token;
$ad_account_id;
$app_secret;
$app_id;
$api = Api::init($app_id, $app_secret, $access_token);
$api->setLogger(new CurlLogger());
$fields = array(
'frequency',
'actions:link_click',
'call_to_action_clicks',
'actions:tab_view',
);
$params = array(
'level' => 'adset',
'filtering' => array(array('field' => 'delivery_info','operator' => 'IN','value' => array('inactive','active','limited','archived','permanently_deleted','completed','recently_completed','not_delivering','not_published','rejected','recently_rejected','rejected','pending_review','scheduled'))),
'breakdowns' => array('place_page_id'),
'time_range' => array('since' => '2017-09-20','until' => '2017-10-20'),
);
echo json_encode((new AdAccount($ad_account_id))->getInsights(
$fields,
$params
)->getResponse()->getContent(), JSON_PRETTY_PRINT);
However, when running the code I get the error message:
Fatal error: Uncaught exception
'FacebookAds\Http\Exception\AuthorizationException' with message
'(#100) Filtering field delivery_info is invalid.
I try switching around in $fields and $params with parameters found in the documentation, but it switches the blame on other ones as I do, even claiming that some of them don't even exist as alternatives.
I've checked several times in the documentation, it should work.
Does the problem lie elsewhere, is it the wrong kind of ad account ID?
Any help would be very much appreciated.
Try adset.delivery_info instead of just delivery_info. That should work. I learned the hard way, seems like you need to append the object level separated by period for filtering options.

How to use google ads api access on behalf your client

im new in googleads library and im facing a problem
i added the google adswords api library to a new laravel 5.3 .
i make a call and retrieve data using the ini file but when i try to use the access on behalf of your client in
this wiki of the library
but it not working the final part i didnt understand
4. You can now use the OAuth2 object to make calls using the client library.
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
$session = (new AdWordsSessionBuilder())
->fromFile()
->withOAuth2Credential($oauth2)
->build();
$adWordsServices = new AdWordsServices();
$campaignService =
$adWordsServices->get($session, 'CampaignService', 'v201603', 'cm');
// Make calls using $campaignService.
when i try the code in the examples they given it give me error Undefined variable: oauth2
i try to put it from the connection file in session and retrieve it in the example file but not worked
one more question :
where i put the ClientCustomerId in on behalf of your client ??
Thanks
First of all, you are missing a small step. you need to OAuth2 instance as indicated in the tutorial like,
session_start();
$oauth2 = new OAuth2([
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
'redirectUri' => '****',
'clientId' => '****',
'clientSecret' => '****',
'scope' => '****'
]);
ClientCustomerId should be placed in adsapi_php.ini file which you can find on Github.
after a while i discover the answer to my questions :
first :
when i try the code in the examples they given it give me error Undefined variable: oauth2
i try to put it from the connection file in session and retrieve it in
the example file but not worked
the answer of this question is in the wiki they make the code in one file. so if you want to put the code work put it in one file . and if you want to put it in other file or use one oauth2 for several files you need just to pass it
via route request
or via middleware
(laravel 5.* $request->attributes->add(['the_name_you_want' => $client]);
and you can retrieve it via this code $client = \Request::get('the_name_you_want') )
for the second question :
where i put the ClientCustomerId in on behalf of your client ??
this is easy to find just put it in the selector part like this
$session = (new AdWordsSessionBuilder())
->fromFile()
->withClientCustomerId('xxx-xxx-xxxx') //change it to what you want
->withOAuth2Credential($client)
->build();
and this is the final of my questions
thanks for helping for who's try to ;)

Marketing Api Permission Exception

I need to get some automated ad insights using the Marketing Api. For this purpose I have created a System User via the Business Manager, and generated a System User access token with the ads_read permission.
Using this token then to make api calls and get a specific Campaign's Insights, with the FacebookAds php v2.6 sdk, I get the following error:
Uncaught exception 'FacebookAds\Http\Exception\PermissionException'
with message '(#275) Cannot determine the target object for this
request. Currently supported objects include ad account, business
account and associated objects.'
Does my app need to be whitelisted or am I missing something else? I noticed that next to the 'ads_read' permission there was this note that stated '(your App must be whitelisted)'.
Here is the sample code I'm using
<?php
define('VENDOR_DIR', 'vendor/'); // Path to the Vendor directory
$loader = require VENDOR_DIR.'autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\Campaign;
// Initialize a new Session and instantiate an Api object
Api::init(
'xxxxxxxxxxxxxxxx', // App ID
'xxxxxxxxxxxxxxxxx',
'xxxxxxxxxxxxxxxxxx' // System User Access Token
);
$api = Api::instance();
use FacebookAds\Object\Values\InsightsLevels;
$campaign = new Campaign('xxxxxxxxxxxxx');
$params = array(
'level' => InsightsLevels::CAMPAIGN,
);
$async_job = $campaign->getInsightsAsync(array(), $params);
$async_job->read();
while (!$async_job->isComplete()) {
sleep(1);
$async_job->read();
}
$async_job->getResult();
?>
It seems like your app doesn't have ads_read permission. Here you can find more information on how to ask for it: https://developers.facebook.com/docs/marketing-api/access

Facebook PHP SDK - Getting error when posting to facebook page but post is created

I don't know why but I get the following error when I'm trying to post to a facebook page that I've created:
Fatal error: Uncaught exception 'Facebook\FacebookAuthorizationException' with message 'Unsupported post request.
Here's the code that I currently have:
<?php
session_start();
require 'vendor/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
FacebookSession::setDefaultApplication('my-app-id', 'my-app-secret');
$session = new FacebookSession('my-access-token');
if($session){
$request = new FacebookRequest($session, 'GET', '/me/accounts?fields=name,access_token,perms');
$pageList = $request->execute()->getGraphObject()->asArray();
$token = $pageList['data'][0]->access_token;
$request2 = new FacebookRequest(
$session,
'POST',
'/my-page-id/feed',
array (
'access_token' => $token,
'name' => 'MySQL: Why My?',
'caption' => 'MySQL: Why My?',
'link' => 'http://www.vertabelo.com/blog/mysql-history',
'message' => 'MySQL: Why My?',
)
);
$response2 = $request2->execute();
print_r($response2);
}
An error is returned but the post is actually posted in the facebook page when I check. Am I doing something wrong here?
Another alternative that I tried is to get the page access token from another page load and then set it on the new FacebookSession call instead of the access token of my profile. Then I omit the access_token in the request for creating a new post. It also returns an error but the post is also created on the page. Any ideas?
This is specifically related to POSTing the link field to the /{page-id}/feed endpoint.
This error is returned when your app is in development mode. If you make the app live, it should work.
Pretty sure this is not the intended behavior, so I submitted a bug report.
I also seen similar kind of errors, when i was writing code for to develop Facebook APP.
I used same idea, made another call to get fresh access token. Then made Graph API call with newly created token. This worked for me, and also my app was still in development mode.
I seen code and think that you are passing parameters in Graph API URI these are not needed to make call. Don't use like this
$request = new FacebookRequest($session, 'GET','/me/accounts?fields=name,access_token,perms');
Instead try this
$request = new FacebookRequest($session, 'GET', /me/accounts');
Happy Coding!
Atul Jindal

Issues using pubnub access manager to publish with php

I am trying to use pubnub with their access manager to authorize certain users to a specific channel and then publish a message to the channel after the user has been granted read/write rights. I must be doing something wrong with the publish() call on this after granting access to the user. The first part of code below returns what looks like a successful response for the grant() but the publish() call results in :
Fatal error: Call to undefined method access::publish() in /home/dayfv98/public_html/mobile/pubtest.php on line 48
Here is my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require('pubnub.php');
require('pam.php');
$chat_entry = addslashes(trim($_POST['chat_entry']));
// CONNECT TO ACCESS MANAGER
$manager = new access(
"MY_PUB_KEY...not included for security",
"MY_SUB_KEY...not included for security",
"MY_SEC_KEY...not included for security"
);
## Grant User Access
print_r($manager->grant(
"chat", // CHANNEL
"44444", // STRING (AUTH KEY)
true, // READ
true, // WRITE
0 // TTL in MINUTES
));
$manager->publish(array(
'channel' => 'chat', ## REQUIRED Channel to Send
'message' => $chat_entry
));
?>
The access manager library is not intended to be used to do anything outside of the scope of the access manager. It is only intended for grants, revokes, and audits.
You will need to use the normal PubNub sdk, but when constructing your PubNub object, provide the auth token you have previously granted.
**EDIT : ** The PHP SDK seems to have some issue with Access Manager right now. I've done some minor hotfix modifications to address this and have included them into a gist, but please keep an eye on the official repository on github for a newer version : https://gist.github.com/keyosk/9c86b981948a3cf7f378
For instance, to use the auth token you granted in your example above, you would do this :
$pubnub = new Pubnub(array(
'publish_key' => 'MY_PUB_KEY',
'subscribe_key' => 'MY_SUB_KEY',
'auth_token' => '44444',
));
$pubnub->publish(array(
'channel' => 'chat',
'message' => $chat_entry
));

Categories