Facebook ads insights API - get basic metrics - facebook-graph-api

I would like to connect to the Facebook Ads Insights API with google scripts in order to generate and update a google sheet containing my ads key performance indicators.
I have read Facebook's documentation but I'm a bit lost, for example In the documentation's website, I can see that I am supposed to follow this syntax to get a campaign's impressions
GET <AD_OBJECT>/insights?fields=impressions
but I'm not quite sure where that would fit in a cURL get query, should it look like this ?
https://graph.facebook.com/v2.5/CAMPAIN_ID/insights?fields=impressions%?access_token=TOKEN
I have tried to build the following google script but I'm not sure it's getting anywhere, any help ?
var myClientID = '';
var myClientSecret = '';
var myAccessToken = 'MY_TOKEN';
var graphURL = 'https://graph.facebook.com/v2.5/';
function getPageLikes(campaign_id) {
var searchParams = '?fields=impressions%2Cunique_clicks%2Creach';
var campaignID = MY_CAMPAIGN_ID;
var fullURL = graphURL + campaignID + '/insights/' + searchParams + '&access_token=' + myAccessToken;
var fetchResult = UrlFetchApp.fetch(fullURL);
var campaign = JSON.parse(fetchResult);
var likes = campaign.data[0];
return campaign_data;
}
Thank you

Yes. If you like CURL, you should play with https://developers.facebook.com/tools/explorer/
Then you can formulate something like:
https://graph.facebook.com/v2.9/[campaign_id]/insights?fields=impressions%2Creach&access_token=[token]
But if you want an easier life, I would recommend you to use one of the SDK. There is one for
PHP: https://github.com/facebook/facebook-php-ads-sdk
Python: https://github.com/facebook/facebook-python-ads-sdk
Java: https://github.com/facebook/facebook-java-ads-sdk
And we also have a tool to guide you generate code in the Getting Started session in https://developers.facebook.com/apps/[app_id]/marketing-api/
Basically you can pick metrics and the wizard will generate a working code for you. (It is only generating Java code for now)
Also if you don't really wants to code, you may try the new product we just released called Facebook Ads Manager for Excel. It allows you to download Insights data into Excel directly. More info:
https://www.facebook.com/business/m/facebook-ads-manager-for-excel

Related

Whats best way of getting content from SharePoint to AWS/Azure programmatically?

How do we move from sharepoint to AWS estate?
I have found various sources on how to do it in the UI, but nothing programmatically?
Any suggestions would be greatly appreciated
Here are UI steps I've found but nothing programmatically - https://www.youtube.com/watch?v=VW6gqVsvOeQ
You should be able to do this in code using the Graph APIs. In particular, you'll be looking for the Working with files in Microsoft Graph section of the API documentation.
Follow these steps to install the Graph SDK.
Follow these steps to Create an app registration.
Follow these steps to Add a certificate to the app registration.
Get an auth token in your code.
Get the site ID by appending /_api/site/id to the site url e.g. https://contoso.sharepoint.com/sites/TheSite/_api/site/id
Get the list of drives associated with the document libraries on your site.
For each drive, get a list of children.
Iterate each child recursively to expand through folders and sub folders.
Download items.
Upload items to AWS.
Getting an auth token
using Azure.Identity;
var scopes = new[] { "https://graph.microsoft.com/.default" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";
// Values from app registration
var clientId = "YOUR_APP/CLIENT_ID";
var clientCertificate = new X509Certificate2("MyCertificate.pfx");
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// https://learn.microsoft.com/dotnet/api/azure.identity.clientcertificatecredential
var clientCertCredential = new ClientCertificateCredential(
tenantId, clientId, clientCertificate, options);
var graphClient = new GraphServiceClient(clientCertCredential, scopes);
Get list of drives
var drives = await graphClient.Sites["{site-id}"].Drives
.Request()
.GetAsync();
Get root items of a drive
var children = await graphClient.Drives["{drive-id}"].Root.Children
.Request()
.GetAsync();
Get children of items
var children = await graphClient.Drives["{drive-id}"].Items["{driveItem-id}"].Children
.Request()
.GetAsync();
Download files
var stream = await graphClient.Me.Drive.Items["{driveItem-id}"].Content
.Request()
.GetAsync();

AWS signature version 2 using javascript

I want to consume AWS product advertising API, I stuck with generating Signature.
Can someone please post the code snippet for creating signature using Javascript.
I had the same issue until last hour ago. After googling many links. Finally i found solution for it.
My solution is here
var Message = "GET" + "\n" + "elasticmapreduce.amazonaws.com" +"\n"+ "AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&Action=DescribeJobFlows&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2011-10-03T15%3A19%3A30&Version=2009-03-31";
var secret = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
var hash = CryptoJS.HmacSHA256(Message, secret);
document.write(hash);
document.write("|| and ||");
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
document.write(hashInBase64);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha256.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/enc-base64.js"></script>
You can verify your signature from https://mws.amazonservices.com/scratchpad/index.html
But beaware of timestamp. Signature vary depends on timestamp

UrlFetch failed because too much traffic is being sent to the specified URL

I'm writing a script for Google Sheets that uses Facebook's Graph API to get my data. Everything worked earlier today but suddenly I'm getting an error:
UrlFetch failed because too much traffic is being sent to the
specified URL.
I haven't hit any quotas about using UrlFetch because I can still fetch from other urls that are not graph.facebook.com - so the issue appears to be specifically with Facebook.
Script Code
var myClientID = '';
var myClientSecret = '';
var myAccessToken = '';
var graphURL = 'https://graph.facebook.com/v2.3/';
function getPageLikes(campaign_id) {
var searchParams = '/stats?fields=actions';
var campaignID = campaign_id;
var fullURL = graphURL + campaignID + searchParams + '&access_token=' + myAccessToken;
var fetchResult = UrlFetchApp.fetch(fullURL);
var campaign = JSON.parse(fetchResult);
var likes = campaign.data[0].actions.like;
return likes;
}
Google Sheet Formula
=getWebClicks('E2')
I discovered a solution after a little more research. I added the 'useIntranet' option as a parameter to fetchResult and that seemed to solve the issue. I imagine the request is now being sent from another resource that doesn't limit requests to Facebook's Graph API.
If anyone can explain why this fixed my problem, that would be great as well!
var options = {"useIntranet" : true};
var fetchResult = UrlFetchApp.fetch(fullURL, options);
I don't have Facebook so I can't try this, replace var fetchResult = UrlFetchApp.fetch(fullURL); with:
do{
var fetchResult = UrlFetchApp.fetch(fullURL);
}while(fetchResult == 'UrlFetch failed because too much traffic is being sent to the specified URL.');
Or anything that matches this error object.
The correct answer is: just wait until the ban gets lifted.

How to login into a third-party website using google app script and manage data on login?

I am interested in creating a google app script that on run would login into a specific website (third-party) and complete certain functions within the website (pressing buttons/copying text).
After browsing the stackoverflow and other forums I have created a script that allows me to login into my website (source1 source2).
However, I am having difficulties staying logged in and managing the data.
//The current code is just testing if I can get data from within the website.
//The results are displayed in a google app.
function doGet() {
var app = UiApp.createApplication();
app.add(app.createLabel(display_basic_data()));
return app;
}
//logins into website and displays data
function display_basic_data() {
var data;
var url = "http://www.website.bla/users/sign_in";
var payload = {"user[username]":"usr","user[password]":"ps"};
var opt ={"method":"post","payload":payload, "followRedirects" : false};
var response = UrlFetchApp.fetch(url,opt);
data = response;
return data;
}
Currently, the data returned from display_basic_data() is
"<html><body>You are being redirected.</body></html>".
If I try to change my script so that "followRedirects" is true, the data is equivalent to the HTML of the login page.
I understand I have to play around with cookies in order to 'stay' logged in but I have no idea what to do as the examples online provided to be fruitless for me.
Any help would be much appreciated!!!
You may want to do something like this:
var cookie = response.getAllHeaders()['Set-Cookie'];
//maybe parse cookies here, depends on what cookie is
var headers = {'Cookie':cookie};
var opt2 = {"headers":headers};
var pagedata = UrlFetchApp.fetch("http://www.website.bla/home",opt2);

Google Analytics missing __utmz cookie

I have universal analytics installed on my website, and want to parse the __utmz cookie to get referral info. However, I never see this cookie set.
Has something changed? Any reason this isn't set?
I do see the _ga cookie when I browse my site, and I see the __utmz cookie in my browser cache if I go to other sites.
I checked out the docs, and don't see any reference to this changing recently, so a bit stumped.
Universal Analytics doesn't create any __utm* cookies.
However, you can use Universal Analytics code (analytics.js) AND the traditional code (ga.js) simultaneously on your site. This will allow you to populate your UA profile and scrape the values from __utmz.
It seems like with Universal Analytics, this cookie has disappeared, and you only get a single _ga cookie.
Source: https://developers.google.com/analytics/devguides/collection/analyticsjs/cookie-usage
Also mentioned here: How to get the referrer, paid/natural and keywords for the current visitor in PHP with new Google Analytics?
Also given that analytics is primarily a tool to collect aggregated information, I couldn't find (and I doubt) that there is any way to query GA to get this info back, given the _ga cookie.
You can create your own cookie and store the query string parameters that google analytics use (utm_campaign and etc).
See this project as example:
https://github.com/dm-guy/utm-alternative
Use below code to get utmz cookie along with your universal analytics js code
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>