sending notifications to user's friend in facebook using js sdk - javascript

I am trying to send notification to user's friend using js sdk on facebook canvas app
but I get this in console
POST https://graph.facebook.com/16542203957691/notifications? 400 (OK) jquery.min.js:140
c.extend.ajax jquery.min.js:140
c.extend.post jquery.min.js:133
makePost ec2-34-41-111-91.ap-southwest-8.compute.amazonaws.com/:69
onclick
I am calling makePost function passing it the friend's profile Id as the argument, this is what I am trying
function makePost(personid){
var accesstoken = FB.getAuthResponse()['accessToken'];
var address = "https://graph.facebook.com/" + personid + "/notifications?";
var tempdata = {};
tempdata['access_token'] = accesstoken;
tempdata['href'] = "";
tempdata['template'] = "You have earned 5 credits, Click here to redeem";
jQuery.post(address, {json: JSON.stringify(tempdata)}, function(data){
console.log(data);
});
}
the person is not receiving the notification.

the problem was that its not the normal access token, here the access token will be a combination of your app id and app secret separated by "|" symbol.
also you need to send the data as an array and not as a json object.
So here is what the working code looks like.
function makePost(personid){
var address = "https://graph.facebook.com/" + personid + "/notifications";
var tempdata = {};
tempdata['access_token'] = appId + "|" + appSecret;
tempdata['href'] = "";
tempdata['template'] = "You have earned 5 credits, Click here to redeem";
jQuery.post(address, tempdata , function(data){
console.log(data);
});
}
PS: I am using Jquery Library to make the post request, So dont forget to include jquery.

Related

Stripe API - Workaround for case sensitive email

I'm using the Stripe API and this is using the customer email address in the database however we've just had an issue where someone is signing in to the page using a different case to their sign up and it is not showing them as subscribed.
Obviously I'd like to convert the Stripe emails to all be lowercase but I'm not sure how to do this after getting the email. I am converting the user input to be all lowercase but that just means that if the email in Stripe is not lowercase they are not showing as subscribed.
Thanks in advance
$(document).ready(function() {
var productIDFull = "prod_key00000";
var email = '#User.Identity.Name';
var emailLower = email.toLowerCase();
// check if user has made a purchase in stripe for this product
var hasPurchasedFull = false;
$.ajax({
type: "GET",
url: 'https://api.stripe.com/v1/customers?email=' + emailLower,
headers: {
'authorization': 'Bearer sk_live_0000'
},
success: function(data) {
var isSubscribed = false;
// loop through each customer returned
$.each(data.data,
function(i, customer) {
console.log(customer);
var subscriptions = customer.subscriptions;
console.log(subscriptions);
// loop through each sub
$.each(subscriptions.data,
function(j, subscription) {
console.log(subscription);
var subData = subscription.items.data;
// loop through each plan
$.each(subData,
function(k, planData) {
console.log(planData);
if (planData.plan.product == 'prod_Kc3e_0000' && planData.plan.usage_type == 'licensed') {
isSubscribed = true;
}
});
});
I am converting the user input to be all lowercase but that just means
that if the email in Stripe is not lowercase they are not showing as
subscribed.
This sounds expected based on Stripe's documentation: https://stripe.com/docs/api/customers/list?lang=curl#list_customers-email
The email value is case sensitive, so customer Test#example.com will not be returned if you list customers with email test#example.com
I think a better way to handle this is to store a mapping of Stripe customer IDs and email addresses in an internal database and compare against this database instead of a customer list call.

Create SharePoint document location using Client API (JavaScript) in Powerapps

In a model-driven powerapp I’m trying to create SharePoint document location using JavaScript and Client API that should be related to a custom entity.
Here is my code:
**//creates records in table via WebAPI call
function createRecordForTable(tableName, dataObj) {
// create table record
Xrm.WebApi.createRecord(tableName, dataObj).then(
function success(result) {
console.log("Record created with ID: " + result.id);
},
function (error) {
console.log(error.message);
}
);
}
//myresponse is object that holds some of needed values
//hel__exceptions is custom entity
const data = new Object();
data.name = myresponse.name;
data.relativeurl = myresponse.relativeurl;
data.absoluteurl = myresponse.absoluteurl;
data["parentsiteorlocation_sharepointdocumentlocation#odata.bind"] = "/sharepointdocumentlocations/(" + myresponse.sharepointdocumentlocationid + ")";
data["regardingobjectid_hel__exceptions#odata.bind"] = "/hel__exceptionses/(" + exceptionId +")";
data.sitecollectionid = myresponse.sitecollectionid;
createRecordForTable("sharepointdocumentlocation", data);**
The error received is: Empty segment encountered in request URL. Please make sure that a valid request URL is specified.
It looks like I’m missing some data that I need to pass with the call Xrm.WebApi.createRecord in order to create the record in sharepointdocumentlocation table.
Please help!

How to post an image to facebook page using Google App Script's facebook snippet?

I am trying to setup a small application based on Google App Script and Google sheets
So far I am able to get the facebook page feed and able to connect to facebook app through Oauth2 library and got the tokens
So I am struggling to write the code for posting to facebook ,
Currently I got the facebook page feeds but the post format documentation from facebook is referring to javascript SDK , and here I am not using SDK and graph API refers with POST and GET requests I think that also didn't work here .
So this is my Codes for getting facebook token and page feed .
Some one referred this as a duplicate but those question and answer doesn't fit in my question , I want facebook post format if it is with payload kindly include those payload options or someone can edit below code for POST
I am able to post to pages with the page access token not user access token
and pasting that page access token also throws the same error .
Updated Code But error appears as follows
Request failed for https://graph.facebook.com/v3.2/PAGE/feed?message=hello?access_token=TOKEN returned code 403. Truncated server response: {"error":{"message":"(#200) If posting to a group, requires app being installed in the group, and \\n either publish_to_groups permission... (use muteHttpExceptions option to examine full response) (line 53, file "FB postinf")
code updated
function example() {
var service = getService();
if (service.hasAccess())
var data = {
"message" : "Me Testing",
//"slug" : "me-testing",
// "text_to_subscribe" : "true"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
var url = "https://graph.facebook.com/v3.2/PAGENAME/feed?message=hello?access_token=ManuallyPastedTOKEN";
// + '?access_token=' + encodeURIComponent(service.getAccessToken());
var response = UrlFetchApp.fetch(url, options);
}
This is using OAuth2 GET FEED
function sasublish(){
var service= getService()
if (service.hasAccess()) {
var url = 'https://graph.facebook.com'
+ '/pagename/feed'
+'?fields='+ encodeURIComponent("name,full_picture,message,attachments{subattachments,url}")
+'&access_token='+ service.getAccessToken();
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
}
Need oAuth2 And Facebook.gs snippet you can use
.setScope('publish_pages,manage_pages,pages_show_list')
should be added to facebook.gs link to facebook.gs snippet
function example() {
var service = getService();
if (service.hasAccess())
var urls ='https://graph.facebook.com/v2.6/PAGEID?fields=access_token'; //specified page token
// var url = 'https://graph.facebook.com/v2.6/me/accounts?'; //tokens along with pages
var response = UrlFetchApp.fetch(urls, { //make url and urls changes
headers: {
'Authorization': 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result , null, 2));
//Logger.log(JSON.stringify(result.data[0].access_token))
var datas = {
"message" : "Me Testing",
//"slug" : "me-testing",
// "text_to_subscribe" : "true"
};
var payload = JSON.stringify(datas);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
var url = "https://graph.facebook.com/v3.2/PAGEID/feed"
+ '?access_token=' + encodeURIComponent(result.data[0].access_token);
// + '?access_token=' + encodeURIComponent(result.access_token);//direct pagetoken
var response = UrlFetchApp.fetch(url, options);
Logger.log('successfully posted to facebook page ',response)
}

How do I get “any valid access_token” for reading public posts?

I need to show the newest 5 posts from my facebook application, and I need to avoid running any server-side code. The following worked until this morning:
var id = myappid;
var limit = 5;
var div = document.getElementById('facebook_posts');
FB.init();
FB.api('/'+id+'/posts', {'limit': limit}, function(response) {
if (response && response.data && response.data.length) {
div.innerHTML = '';
for (var i=0, l=response.data.length; i<l; i++) {
var post = response.data[i];
if (post.message && post.link)
div.innerHTML += '' + post.message + '<br/>';
}
} else {
div.innerHTML = 'Error loading facebook posts';
}
});
I didn't change anything, but now facebook returns an "OAuthException" with the message "An access token is required to request this resource.". The API says I need "Any valid access_token to see public". So, how do I get "Any valid access_token" without showing an authendication pop-up?
The easiest thing would be to use an offline access token created for your administrator user. Look here to find out how to create one.
You can also use the token that the Facebook graph API explorer uses. But don't grab one from your personal account if you are embedding the token in your page.

Get a List of All Friends on Facebook Using JS SDK and FQL

I am trying to get a list of all friends of the current user using my Facebook application:
Here is my code for your reference:
var meID = <?php echo $data['user_id']; ?>;
var queryOnFriends = "SELECT uid, name, online_presence, status FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = " + meID + ")";
var queryOnFriends1 = "SELECT uid, name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=" + meID + ")";
var queryOnFriends2 = "SELECT uid2 FROM friend WHERE uid1 = me()";
var queryUserName = "SELECT name, uid FROM user WHERE uid={0}";
var query = FB.Data.query(queryOnFriends2, meID);
query.wait(function(rows){
alert("in callback");
document.getElementById('display').innerHTML =
'Your name is ' + rows[0].name;
});
Referring to my attempt using var queryUserName works fine, but all the others didn't work, even the simple queryOnFriends2 from the FQL examples.
The application asks for permissions correctly (read_friendlists, user_online_presence, friends_online_presence) and the FB JS SDK seems to initialize well, as querying for the user's own username (queryUserName) works, however, it does not even execute the callback function in the failing cases!
What am I doing wrong?
The difference between queryUserName and your other queries is that queryUserName contains a parameter, the {0}.
Your other queries are using me() instead, so they don't need a data parameter to be passed in.
You need to change this line:
var query = FB.Data.query(queryOnFriends2, meID);
to this:
var query = FB.Data.query(queryOnFriends2);
OK i got it now ... i used php to authorize my app ... but didn't authenticate as well! When using just the facebook jsSDK and initalize and then getStatus it does it all automaticly!
Then the queries worked!

Categories

Resources