Upload email list to Facebook via API - facebook

I need to send or create the list of user emails to our business facebook account as an audience list ,so that we can use it for our marketing purposes(I'm using Python 3.8).
Below is the code which i got from Google, But when i searched i found that we cannot directly pass the emails to Facebook via API.
Do you have any suggestions on how to achieve it ?
Also "can i pass email ID's to this list "fields = [] in the below code ?
AND what does the "ID" means ?
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.customaudience import CustomAudience
from facebook_business.api import FacebookAdsApi
access_token = 'EAAi0wZCiZxxxxxxxxxxxxxxxDZD'
app_secret = 'xxxxxxxxxxxxxxx'
app_id = 'xxxxxxxxxxx'
id = '<ID>'
fields = []
FacebookAdsApi.init(access_token=access_token)
print("Access succesful")
params = {
'name': 'My new Custom Audience',
'subtype': 'CUSTOM',
'description': 'People who purchased on my website',
'customer_file_source': 'USER_PROVIDED_ONLY',
}
print (AdAccount(id).create_custom_audience(
fields=fields,
params=params,
))

You should first create the Custom Audience like you already do, then you can add/remove emails with the SDK API (you do not need manually hash the email: the SDK will do it for you). As example:
custom_audience = CustomAudience(DocsDataStore.get('ca_id'))
response = custom_audience.add_users(
schema=CustomAudience.Schema.email_hash,
users=[
'joe#example.com',
]
)
If you take a look of the SDK DOC Here:
CustomAudience.add_users (schema, users, is_raw, app_ids, pre_hashed)
pre_hashed: Whether or not the data has already been hashed. If not, the SDK will automatically hash the data
See also the SDK Doc TestCase here

Related

Facebook Marketing API - Object with ID does not exist

I started with Facebook Marketing API today.
I am simply trying to read the campaigns from my Facebook Business account. I have an Ad account and a Campaign created there.
I suppose my issue is with generating the Token.
I am simply generating the token from here: https://developers.facebook.com/tools/explorer?classic=0
And the error I get is:
{ error:
{ message: 'Unsupported get request. Object with ID \'10xxxxxxxx\' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api',
type: 'GraphMethodException',
code: 100,
error_subcode: 33,
fbtrace_id: 'E5CAU6UvHwF' } }
My Node.js code is:
const readCampaign = async (program) => {
const accessToken = TOKEN
const api = adsSdk.FacebookAdsApi.init(accessToken)
const account = new AdAccount('act_' + program.accountid)
console.log('act_' + account.id) // fields can be accessed as properties
let result
account.read([AdAccount.Fields.name])
.then((account) => {
return account.getCampaigns([Campaign.Fields.name], { limit: 10 }) // fields array and params
})
.then((result) => {
campaigns = result
campaigns.forEach((campaign) => console.log(campaign.name))
}).catch(console.error);
console.log(result)
}
To generate the Token I am choosing the App I created, "Get User Access Token" and then selected all possible permissions there - just to test this.
What am I doing wrong? Thanks
I suspecting this is due to a permission error.
First I would check that your app has access to the account you are trying to access.
Then I would suggest creating a system user through your business manager (can be found under business settings ), assigning it access to ad accounts, and utilizing the the system user's token when initializing the library.
One big advantage is that the system users's token does not have such a short expiration time.
Facebook system user doc

Add a subpanel record to a SugarCRM account through REST API

Question: How do I create a subpanel record through the SugarCRM rest api endpoint for accounts?
Steps taken so far:
I've added a new package called, "transactionHistory" with a module named, "InvoiceHistory" using the SugarCRM studio.
I added a One to Many relationship to the Accounts module using studio.
I'm using NetSuite to push new invoices to the new module's record via the subpanel "create" option. Here's the code I'm using:
function createSugarTransaction(transaction, token) {
var url = 'https://crm.techsoft3d.com/rest/v10/Accounts/' + transaction.customer;
var headers = {
"Content-Type": "application/json",
"OAuth-Token": token
};
var now = (new Date()).toISOString();
var body = {transactionHistory_InvoiceHistory:
{
create: [{
name: transaction.docId,
transaction_date_c: transaction.date,
invoice_status_c: transaction.status,
due_date_c: transaction.duedate,
total_amount_c: transaction.total,
amount_due_c: transaction.remaining,
start_date_c: transaction.startdate,
end_date_c: transaction.enddate
}]
}
};
var response = nlapiRequestURL(url, JSON.stringify(body), headers, 'PUT');
return response;
}
The transaction object has been validated and the json object within the create: [] array has matching sugar fields (key) with the corresponding transaction object values.
When making the API call to sugar I'm successfully authenticated and have access to the custom module and accounts - so no problem there. However, when the call is returned to response it's showing the following error:
{"error":"no_method","error_message":"Could not find a route with 1 elements"}
I'm unsure of what else is needed in order for the record to be created. According to sugar's help documentation and developer community this should work. I'm using the basic information provided by sugarcrm support portal:
http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.6/API/Web_Services/Examples/v10/module_POST/
According to other blog posts within the developer community, it should be as simple as adding the subpanel name, followed by an array of fields under the "create" object... similar to this:
var requestBody = { package_module:create[{name:value}]};
My initial thinking of what's wrong is:
1. my package_module name isn't correct, but I'm unable to find it anywhere within the applicaiton or help documentation.
2. the request body isn't formatted properly, even though it's structure was copied from this article https://developer.sugarcrm.com/2014/02/28/sugarcrm-cookbook2/
Any help would be appreciated.
try the createRelatedRecord api endpoint
type {sugarurl}/rest/v10/help to see a list of endpoints to look through, most of which have documentation and examples
https://crm.techsoft3d.com/rest/v10/help
your API url should have the name of the link (relationship) you want, in addition to the values in the POST payload
https://crm.techsoft3d.com/rest/v10/Accounts/{transaction.customer}/link/accounts_transactionhistory (or whatever your link's name is)
per the documentation for this endpoint, you just specify the field values in the payload
{
"first_name":"Bill",
"last_name":"Edwards"
}

Retrieve User ID of Facebook App Invitor

In the context of a given Facebook app, suppose User A invited user B to start using it. Once User B accepts to use the app, is there any way to retrieve the ID of User A programmatically (via either PHP/JS SDK) ? This doesn't seem quite documented.
For what it's worth, A/B users are friends, if it's any use.
when user comes following the app request, you can get request id's using
$_GET['request_ids']
then retrieve all the request ids with which you can call graph api to get the corresponding request details like below:
if(isset($_GET['request_ids']))
{
$request_ids = $_GET['request_ids'];
}
$request_ids = explode(",", $request_ids);
foreach($request_ids as $request_id)
{
$request_object = $facebook->api($request_id);
//this $request_object have sender facebook id in the field uid_from
}
If you look here:
http://developers.facebook.com/docs/reference/dialogs/requests/
You can see the object layout. Of note is the data property:
Optional, additional data you may pass for tracking. This will be
stored as part of the request objects created. The maximum length is
255 characters.
In this object you can add your referring UserId and then when the request is claimed, you can then process it on your end.
Hope this helps.

facebook graph api check if user is a member of a group using PHP

i want to check if a user is a member of a group using facebook graph api...
i have this:
$group = file_get_contents("https://graph.facebook.com/177129325652421/members?access_token=XXXXXXXX");
$group = json_decode($group);
$checkuser = $group->data;
and check the user if is a member by using his facebook id and in_array()
if(in_array($_GET["fid"],$checkuser)){
echo "yes";
} else {
echo "no";
}
can someone help me to correct this please... my code is not working...
Reference: https://developers.facebook.com/docs/reference/api/
Use the API url:
https://graph.facebook.com/me/groups
To get a user's groups. In the above link, change the me/ to the user's FB ID. You must also pass in an Access Token.
The reply will be JSON encoded. Decode it using json_decode to a PHP Associative array. Iterate over it and check for the group you want.
The Graph API does not return all groups at once. You must either use the pagination links at the end of each response to fetch more, or use the limit parameter to request as many as you need.
The following code sample will post the IDs of the Groups you are a part of
<?php
$url = "https://graph.facebook.com/me/groups?access_token=AAAAAAITEghMBAMDc6iLFRSlVZCoWR0W3xVpEl1v7ZAxJRI3nh6X2GH0ZBDlrNMxupHXWfW5Tdy0jsrITfwnyfMhv2pNgXsVKkhHRoZC6dAZDZD";
$response = file_get_contents($url);
$obj = json_decode($response);
foreach($obj->data as $value) {
echo $value->id;
echo '<br>';
}
/* to check for existence of a particular group
foreach($obj->data as $value) {
if ($value->id == $yourID) {
//found
break;
}
//not found. fetch next page of groups
}
*/
PS - If running the above code gives you an error stating Could not find wrapper for "https", you need to uncomment/add the PHP extension extension=php_openssl.dll
Was looking into this and found this as first answer in google but the answer seems to be much of a hassle so I dug a bit deeper.
The fastest answer I've found which doesn't require iterating through all of the groups' members uses FQL.
SELECT gid, uid FROM group_member WHERE uid = (user id) AND gid = (group id)
This either returns an empty 'data' object, or a 'data' object with the UID and GID.
It also (from what I see so far) , doesn't require the user_groups permission.
https://developers.facebook.com/tools/explorer?fql=SELECT%20gid%2C%20uid%20FROM%20group_member%20WHERE%20uid%20%3D%20551549780%20AND%20gid%20%3D%20282374058542158
This FQL query returns for me:
{
"data": [
{
"gid": "282374058542158",
"uid": "551549780"
}
]
}
This doesn't seem to be possible after Graph API v2.4, because Facebook decided to disallow it:
https://developers.facebook.com/docs/apps/changelog#v2_4
"the user_groups permission has been deprecated. Developers may continue to use the user_managed_groups permission to access the groups a person is the administrator of. This information is still accessed via the /v2.4/{user_id}/groups edge which is still available in v2.4."
It also states "From October 6, 2015 onwards, in all previous API versions, these endpoints will return empty arrays." But it seems to me that it still works on v2.2 & v2.3.

Find Facebook user (url to profile page) by known email address

I have an email address and want to find out if there is a Facebook user linked to this address. If there is, then I want to retrieve the url to this users profile page and save it somewhere.
I do not have a facebook application, but, if necessary, I would use existing account data to login to facebook and perform the task.
I thought this would be an easy task, but somehow it's not. I read through the Graph API documentation and there you find instructions on how to search public data. It says the format is:
https://graph.facebook.com/search?q=QUERY&type=OBJECT_TYPE
But trying this with an email address in the q param and user in the type param without further information results in an OAuthException saying "An access token is required to request this resource."
However, if you click the example search links Facebook generates a url with the mentioned access token related to the currently logged on user. Performing searches with this token gives the expected results. But i cannot figure out how to get this user session access token after logging in. Every time I search on how to get an access token I only find information regarding Facebook apps and retrieving permissions for basic or specific data access. This is, as I mentioned, not what I am looking for, as I don't have and don't need a facebook app.
Since Facebook gives me the needed token in the example links I thought it shouldn't be a problem to get it too. Or do they only have it because of home advantage?
Also, the Outlook Social Connector Provider for Facebook is able to retrieve Facebook data just via an email address (and the account data provided). So I thought, if Microsoft can do this stuff I should be also possible to do simliar things.
Last but not least this is the more frustrating since I, theoretically and practically, am already able to find users profile url just by searching for the email address. I don't even have to be logged on to Facebook. And it's not the official API way.
If I perform a web request to http://www.facebook.com/search.php?init=s:email&q=example#domain.com&type=users I get the expected search result. The problem is that I have to parse the HTML code and extract the url (that's okay) and that the result page is possibly subject to change and could easily break my method to extract the url (problematic).
So does anybody has an idea what's the best way to accomplish the given task?
The definitive answer to this is from Facebook themselves. In post today at https://developers.facebook.com/bugs/335452696581712 a Facebook dev says
The ability to pass in an e-mail address into the "user" search type was
removed on July 10, 2013. This search type only returns results that match
a user's name (including alternate name).
So, alas, the simple answer is you can no longer search for users by their email address. This sucks, but that's Facebook's new rules.
Simply use the graph API with this url format:
https://graph.facebook.com/search?q=zuck#fb.com&type=user&access_token=... You can easily create an application here and grab an access token for it here. I believe you get an estimated 600 requests per 600 seconds, although this isn't documented.
If you are doing this in bulk, you could use batch requests in batches of 20 email addresses. This may help with rate limits (I am not sure if you get 600 batch requests per 600 seconds or 600 individual requests).
In response to the bug filed here: http://developers.facebook.com/bugs/167188686695750 a Facebook engineer replied:
This is by design, searching for users is intended to be a user to user function only, for use in finding new friends or searching by email to find existing contacts on Facebook. The "scraping" mentioned on StackOverflow is specifically against our Terms of Service https://www.facebook.com/terms.php and in fact the only legitimate way to search for users on Facebook is when you are a user.
Maybe this is a little bit late but I found a web site which gives social media account details by know email addreess. It is https://www.fullcontact.com
You can use Person Api there and get the info.
This is a type of get : https://api.fullcontact.com/v2/person.xml?email=someone#****&apiKey=********
Also there is xml or json choice.
I've captured the communication of Outlook plugin for Facebook and here is the POST request
https://api.facebook.com/method/fql.multiquery
access_token=TOKEN&queries={"USER0":"select '0', uid, name, birthday_date, profile_url, pic, website from user where uid in (select uid from email where email in ('EMAIL_HASH'))","PENDING_OUT":"select uid_to from friend_request where uid_from = MY_ID and (uid_to IN (select uid from #USER0))"}
where
TOKEN - valid access token
EMAIL_HASH - combination of CRC32 and MD5 hash of searched email address in format crc32_md5
MY_ID - ID of facebook profile of access token owner
But when I run this query with different access token (generated for my own application) the server response is: "The table you requested does not exist" I also haven't found the table email in Facebook API documentation. Does Microsoft have some extra rights at Facebook?
Andreas,
I've also been looking for an "email-to-id" ellegant solution and couldn't find one.
However, as you said, screen scraping is not such a bad idea in this case, because emails are unique and you either get a single match or none. As long as Facebook don't change their search page drastically, the following will do the trick:
final static String USER_SEARCH_QUERY = "http://www.facebook.com/search.php?init=s:email&q=%s&type=users";
final static String USER_URL_PREFIX = "http://www.facebook.com/profile.php?id=";
public static String emailToID(String email)
{
try
{
String html = getHTML(String.format(USER_SEARCH_QUERY, email));
if (html != null)
{
int i = html.indexOf(USER_URL_PREFIX) + USER_URL_PREFIX.length();
if (i > 0)
{
StringBuilder sb = new StringBuilder();
char c;
while (Character.isDigit(c = html.charAt(i++)))
sb.append(c);
if (sb.length() > 0)
return sb.toString();
}
}
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private static String getHTML(String htmlUrl) throws MalformedURLException, IOException
{
StringBuilder response = new StringBuilder();
URL url = new URL(htmlUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
BufferedReader input = new BufferedReader(new InputStreamReader(httpConn.getInputStream()), 8192);
String strLine = null;
while ((strLine = input.readLine()) != null)
response.append(strLine);
input.close();
}
return (response.length() == 0) ? null : response.toString();
}
This is appeared as pretty easy task, as Facebook don't hiding user emails or phones from me. So here is html parsing function on PHP with cURL
/*
Search Facebook without authorization
Query
user name, e-mail, phone, page etc
Types of search
all, people, pages, places, groups, apps, events
Result
Array with facebook page names ( facebook.com/{page} )
By 57ar7up
Date 2016
*/
function facebook_search($query, $type = 'all'){
$url = 'http://www.facebook.com/search/'.$type.'/?q='.$query;
$user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36';
$c = curl_init();
curl_setopt_array($c, array(
CURLOPT_URL => $url,
CURLOPT_USERAGENT => $user_agent,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE
));
$data = curl_exec($c);
preg_match_all('/href=\"https:\/\/www.facebook.com\/(([^\"\/]+)|people\/([^\"]+\/\d+))[\/]?\"/', $data, $matches);
if($matches[3][0] != FALSE){ // facebook.com/people/name/id
$pages = array_map(function($el){
return explode('/', $el)[0];
}, $matches[3]);
} else // facebook.com/name
$pages = $matches[2];
return array_filter(array_unique($pages)); // Removing duplicates and empty values
}
Facebook has a strict policy on sharing only the content which a profile makes public to the end user.. Still what you want is possible if the user has actually left the email id open to public domain..
A wild try u can do is send batch requests for the maximum possible batch size to ids..."http://graph.facebook.com/ .. and parse the result to check if email exists and if it does then it matches to the one you want.. you don't need any access_token for the public information ..
in case you want email id of a FB user only possible way is that they authorize ur app and then you can use the access_token thus generated for the required task.
Maybe things changed, but I recall rapleaf had a service where you enter an email address and you could receive a facebook id.
https://www.rapleaf.com/
If something was not in there, one could "sign up" with the email, and it should have a chance to get the data after a while.
I came across this when using a search tool called Maltego a few years back.
The app uses many types of "transforms", and a few where related to facebook and twitter etc..
..or find some new sqli's on fb and fb apps, hehe. :)
WARNING: Old and outdated answer. Do not use
I think that you will have to go for your last solution, scraping the result page of the search, because you can only search by email with the API into those users that have authorized your APP (and you will need one because the token that FB provides in the examples has an expiry date and you need extended permissions to access the user's email).
The only approach that I have not tried, but I think it's limited in the same way, is FQL. Something like
SELECT * FROM user WHERE email 'your#email.com'
First I thank you. # 57ar7up and I will add the following code it helps in finding the return phone number.
function index(){
// $keyword = "0946664869";
$sql = "SELECT * FROM phone_find LIMIT 10";
$result = $this->GlobalMD->query_global($sql);
$fb = array();
foreach($result as $value){
$keyword = $value['phone'];
$fb[] = $this->facebook_search($keyword);
}
var_dump($fb);
}
function facebook_search($query, $type = 'all'){
$url = 'http://www.facebook.com/search/'.$type.'/?q='.$query;
$user_agent = $this->loaduserAgent();
$c = curl_init();
curl_setopt_array($c, array(
CURLOPT_URL => $url,
CURLOPT_USERAGENT => $user_agent,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE
));
$data = curl_exec($c);
preg_match('/\{"id":(?P<fbUserId>\d+)\,/', $data, $matches);
if(isset($matches["fbUserId"]) && $matches["fbUserId"] != ""){
$fbUserId = $matches["fbUserId"];
$params = array($query,$fbUserId);
}else{
$fbUserId = "";
$params = array($query,$fbUserId);
}
return $params;
}