How to get stats of multiple campaigns in Facebook ads api - facebook-php-sdk

I write the below code for retrieve single campaign stats.
$fields = array(
'start_time','actions','spent','clicks','impressions','end_time',
);
$params = array();
$campaign = new AdCampaign(123456);
$stats = $campaign->getStats($fields, $params);
here I can able to access the stats. But when use this function loop then I got issue like
Calling : $campaign = new AdCampaign($campaign_id);
Error : "An access token is required to request this resource"
But using graph API I can access the multiple campaigns stats at a time
https://graph.facebook.com/stats?ids=123,456,789&fields=start_time,actions,spent,clicks,impressions,end_time&access_token=...
I need it using Ads API .... Please solve it for me..

I think this is a missing feature from the SDK at the moment as you can only access stats relative to an object.
However, calling stats in a loop should not be a problem, assuming you instantiated the API class correctly.
use FacebookAds\Api;
use FacebookAds\Object\AdCampaign;
Api::init($app_id, $app_secret, $access_token);
$campaign_ids = array(...);
$fields = array(
'start_time',
'actions',
'spent',
'clicks',
'impressions',
'end_time',
);
$params = array();
$stats = array();
foreach($campaign_ids as $id) {
$campaign = new AdCampaign($id);
$stats[$id] = $campaign->getStats($fields, $params);
}
You could also just get all stats for all campaigns by using the getAdCampaignStats on AdAccount.

Related

How to fetch data only for a particular user from a database with data multiple users in laravel

I am trying to display data from a database based on the logged in user in laravel.
If there is data for one user everything works well but if another user adds data to the table I get the error Cannot use object of type stdClass as array
Here is how I am getting the data in controller
public function viewBookings() {
$allProducts = Booking::get()->where('client', Auth::user()->name);
$products = json_decode(json_encode($allProducts));
foreach ($products as $key => $val) {
$service_name = Service::where(['id' => $val->service])->first();
$service_fee = Charge::where(['id' => $val->charge])->first();
$service_status = Status::where(['id' => $val->status])->first();
$products[$key]->service_name = $service_name->name;
$products[$key]->service_fee = $service_fee->total;
$products[$key]->service_status = $service_status->name;
}
return view('client.booking.view_bookings')->with(compact('products'));
}
The error is indicated at this line
$products[$key]->service_name = $service_name->name;
I have tested it by deleting the data for the other user and all works fine but If I return the other users data to the table I get that error
I would suggest removing this line
$products = json_decode(json_encode($allProducts));
and simply use
$products = $allProducts;
since what you are doing with the json_decode is the one creating the problems

What I am doing wrong with twitter API?

I am making a widget using https://github.com/j7mbo/twitter-api-php.
My widget is working fine there is no problem in my widget.
So what's the problem:
Inside my TwitterWidget Class whichi is extending WP_Widget inside the widget( $args, $instance ). I have make a function inside :
Here is it:
function get_Connection_With_Twitter_API( $scr_name, $cons_key, $cons_secret, $acce_token_key, $acce_token_secret ) {
$settings = array(
'oauth_access_token' => $acce_token_key,
'oauth_access_token_secret' => $acce_token_secret,
'consumer_key' => $cons_key,
'consumer_secret' => $cons_secret
);
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?screen_name='.$scr_name;
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
// $twitter = new TwitterAPIExchange($settings);
// return $twitter->buildOauth($url, $requestMethod)
// ->setPostfields($postfields)
// ->performRequest();
}
$connection = get_Connection_With_Twitter_API( $instance['twitter_username'], $instance['twitter_consumerkey'], $instance['twitter_consumersecret'], $instance['twitter_accesstoken'], $instance['twitter_accesstokensecret'] );
I am getting this message:
{"errors":[{"code":89,"message":"Invalid or expired token."}]}
What I am doing wrong.
I assume you have your access tokens and you are being careful not displaying them here, and you have created a new app on the twitter account. On that light, I strongly suggest you change the permission of your app to "Read, Write and Direct Message".
For the perfect and most simple and well documented api, I suggest Twit.

WP REST API v2 Can't use filters

I Connecting with woocommerse with Oauth2.
But i can't use filters, example /wp-json/wp/v2/post&filter[category_name]=food
I get information about users, example http://my-site/wp-json/wp/v2/users, but on page i get info about first 10 users, i need more... When i use filter, example : http://my-site/wp-json/wp/v2/users?filter[posts_per_page]=5- filter not work
my code:
require('vendor/autoload.php');
const CLIENT_ID = 'my-ID';
const CLIENT_SECRET = 'my-secret';
const REDIRECT_URI = 'http://wooc/test.php';
const AUTHORIZATION_ENDPOINT = 'http://my-site/oauth/authorize';
const TOKEN_ENDPOINT = 'http://my-site/oauth/token';
$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET);
if (!isset($_GET['code']))
{
$auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
header('Location: ' . $auth_url);
die('Redirect');
}
else
{
$params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI);
$response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code',$params);
}
$client->setAccessToken("a6kpdxqqs3runou66ovzjjy54rvfubv64hhpdomn");
$data = $client->fetch("http://my-site/wp-json/wp/v2/users?filter[posts_per_page]=5");
echo "<pre>";
var_dump($data);
I do not understand where the error!
Please help. thank you
The API response filtering functionality has been superseded by more robust query parameters like ?categories=, ?slug= and ?per_page=.
In WordPress 4.7 the filter argument for any post endpoint was removed, The filter argument allows the posts to be filtered using WP_Query public query vars. This plugin restores the filter parameter for sites that were previously using it: https://github.com/luisfredgs/rest-filter
However, you can also convert your existing code to remove filter.
Something along the lines of this:
http://my-site/wp-json/wp/v2/users?filter[posts_per_page]=5
becomes this:
http://my-site/wp-json/wp/v2/users?posts_per_page=5

Problems while getting custom dimensions via API from Google Analytics

Goog day. When I try to get custom dimensions via API, I got error
Exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/customDimensions:
(400) Cannot query by ~all for id webPropertyId'
My code
$service_account_name = '<Service Email>#developer.gserviceaccount.com';
$key_file_location = '<keyName>.p12';
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array(Google_Service_Analytics::ANALYTICS),
$key,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
'<My email>'
);
$client->getAuth()->setAssertionCredentials($cred);
$service = new Google_Service_Analytics($client);
$result = $service->management_customDimensions->listManagementCustomDimensions('~all', '~all');
print_r($result);
Similar code for getting goals works correctly
$service_account_name = '<Service Email>#developer.gserviceaccount.com';
$key_file_location = '<keyName>.p12';
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array(Google_Service_Analytics::ANALYTICS),
$key,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
'<My email>'
);
$client->getAuth()->setAssertionCredentials($cred);
$service = new Google_Service_Analytics($client);
$result = $service->management_profiles->listManagementProfiles('~all', '~all');
print_r($result);
Both methods listManagementProfiles and listManagementProfiles get parametrs $accountId and $webPropertyId .
Could someone help, why I get error, while getting custom dimensions via API?
Looking at the documentation "~all" is specifically mentioned as valid parameter value for listManagementProfiles:
Account ID for the view (profiles) to retrieve. Can either be a
specific account ID or '~all', which refers to all the accounts to
which the user has access.
but not for listManagementCustomDimensions, here is says simply
Account ID for the custom dimensions to retrieve.
(same for property id). So your problem is quite literally what the error message says, you cannot use "~all" when querying custom dimensions.
So it seems that to list all custom dimensions you'd have to iterate through a list of property ids (as returned by the properties/list method) instead of using "~all".

wordpress site integration with rest API

I'm trying to integrate with zoom.us, they have their guides here - https://support.zoom.us/hc/en-us/articles/201363053-Meeting-API
When someone schedules a meeting, the scheduler creates a post, which I pick up and call this function:
function scheduler_zoom_integration($post_id) {
$postdata = get_post($post_id);
$appointment_id = get_post_meta( $post_id, '_birs_appointment_id', true );
if (!empty($appointment_id)) {
$conference_details = schedule_meeting();
add_post_meta($appointment_id,'appointment_zoom_details', $conference_details, true);
}
}
add_action('publish_post', 'scheduler_zoom_integration');
Inside that function I call the schedule_meeting function that is using the REST API from zoom to get the meeting details including the link people will click to join the meeting.
function schedule_meeting($coach_id, $appointment_id, $start_time) {
$api_key = 'xxxxxxxxxxxxxxxxxxxxxxx';
$api_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$coach_zoom_id = get_user_meta($coach_id, 'coachzoomid', true);
$url = 'https://api.zoom.us/v1/meeting/create?api_key='.$api_key.'&api_secret='.$api_secret.'&data_type=JSON&host_id='.$coach_zoom_id.'&topic=health&type=2&start_time='.$start_time.'&duration=30&timezone=GMT-7:00&option_jbh=true&option_start_type=video';
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$response = fopen($url, 'r', false, $context);
fpassthru($response);
$response = json_decode($response);
fclose($response);
return $response;
}
I'm looking to get feedback on how I'm performing this function as I've never done a REST API before. Should I use fopen / fclose? How do I make the call to begin with? Any help is appreciated.
You should try using WordPress' built in HTTP API. It has helper functions for doing HTTP calls. I see you're doing a GET so check out:
http://codex.wordpress.org/Function_Reference/wp_remote_get
Note that it returns WP_Error class on failure.

Resources