How do I get Gmail contacts using JavaScript? - javascript

What is the Ajax call that I should make to get gmail contacts using JavaScript? I already have the user OAuth Token which I got because the user signed up to my site using Google.

If you're using OAuth2 through JavaScript, you can use the Google Contacts API, but you'll need to get authorisation by sending the correct scope of permissions to Google when getting the access token, which is https://www.google.com/m8/feeds. (reference)
As you already know how to get the access token, it's as simple as calling the API with the correct query. To get all contacts for your user, it's as simple as making an asynchronous request to the API for the required info. For example, where {userEmail} is the user's email and {accessToken} is your access token, simply make a GET address to the following URI:
https://www.google.com/m8/feeds/contacts/{userEmail}/full?access_token={accessToken}&alt=json
A list of the types of queries you can send and their parameters are available here:
Google Contacts API
API Parameters

To get users' contacts using OAuth, first you need to specify the contact's scope in your request. If you're using ChromeExAuth, then you would write:
var oauth = ChromeExOAuth.initBackgroundPage({
'request_url' : 'https://www.google.com/accounts/OAuthGetRequestToken',
'authorize_url' : 'https://www.google.com/accounts/OAuthAuthorizeToken',
'access_url' : 'https://www.google.com/accounts/OAuthGetAccessToken',
'consumer_key' : 'anonymous',
'consumer_secret' : 'anonymous',
'scope' : 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.google.com/m8/feeds/',
'app_name' : 'MyApp'
});
The scope parameter above lists 3 scopes: the user's email, profile, and contacts (google.com/m8/feeds/contacts)
To get their contacts after the user authorizes the token, you would send a request like this:
var url = "http://www.google.com/m8/feeds/contacts/default/full";
oauth.sendSignedRequest(url, onContacts, {
'parameters' : {
'alt' : 'json',
'max-results' : 99999
}
});
And the callback for the request could look like this:
function onContacts(text, xhr) {
contacts = [];
var data = JSON.parse(text);
for (var i = 0, entry; entry = data.feed.entry[i]; i++) {
var contact = {
'name' : entry['title']['$t'],
'id' : entry['id']['$t'],
'emails' : []
};
if (entry['gd$email']) {
var emails = entry['gd$email'];
for (var j = 0, email; email = emails[j]; j++) {
contact['emails'].push(email['address']);
}
}
if (!contact['name']) {
contact['name'] = contact['emails'][0] || "<Unknown>";
}
contacts.push(contact);
}
};
To view the contacts array, you could just print on the console:
console.log(contacts);
You can checkout the Google OAuth tutorial here

Related

Is this domain available or taken? In Google Sheets apps script

I have a list of domains in Google Sheets. I'd like to find out if they are available or not, by looking at Godaddy or similar site.
Here is the apps script function:
function domainavail(url)
{
url = "https://www.godaddy.com/domainsearch/find?checkAvail=1&segment=repeat&domainToCheck="+url;
var options = {
'muteHttpExceptions': true,
'followRedirects': false
};
var response = UrlFetchApp.fetch(url, options);
var html = response.getContentText();
if ( html.match(/Why it's great./) )
return "Y";
return "N";
}
It is trying to match the text "Why it's great." which should only show up on the result page if the domain is available.
However, the function is returning "Y" every time, even for domains that are taken.
Can you help me update this function?
If you just want to know if the domain is existing or not, use Registration Data Access Protocol (RDAP). This doesn't take a while to load as it only returns string. And returns 404 if the domain isn't registered. There are also details there that you might be able to use instead of paying for premium services if you want them.
Code:
function domainavail(url) {
var options = {
'muteHttpExceptions': true,
'followRedirects': false
};
var html = UrlFetchApp.fetch('https://rdap.verisign.com/com/v1/domain/' + url, options).getContentText();
if(html.length == 0)
return "Y";
return "N";
}
RDAP return value (youtube.com):
{"objectClassName":"domain","handle":"142504053_DOMAIN_COM-VRSN","ldhName":"YOUTUBE.COM","links":[{"value":"https:\/\/rdap.verisign.com\/com\/v1\/domain\/YOUTUBE.COM","rel":"self","href":"https:\/\/rdap.verisign.com\/com\/v1\/domain\/YOUTUBE.COM","type":"application\/rdap+json"},{"value":"https:\/\/rdap.markmonitor.com\/rdap\/domain\/YOUTUBE.COM","rel":"related","href":"https:\/\/rdap.markmonitor.com\/rdap\/domain\/YOUTUBE.COM","type":"application\/rdap+json"}],"status":["client delete prohibited","client transfer prohibited","client update prohibited","server delete prohibited","server transfer prohibited","server update prohibited"],"entities":[{"objectClassName":"entity","handle":"292","roles":["registrar"],"publicIds":[{"type":"IANA Registrar ID","identifier":"292"}],"vcardArray":["vcard",[["version",{},"text","4.0"],["fn",{},"text","MarkMonitor Inc."]]],"entities":[{"objectClassName":"entity","roles":["abuse"],"vcardArray":["vcard",[["version",{},"text","4.0"],["fn",{},"text",""],["tel",{"type":"voice"},"uri","tel:+1.2083895740"],["email",{},"text","abusecomplaints#markmonitor.com"]]]}]}],"events":[{"eventAction":"registration","eventDate":"2005-02-15T05:13:12Z"},{"eventAction":"expiration","eventDate":"2022-02-15T05:13:12Z"},{"eventAction":"last update of RDAP database","eventDate":"2021-07-09T09:23:30Z"}],"secureDNS":{"delegationSigned":false},"nameservers":[{"objectClassName":"nameserver","ldhName":"NS1.GOOGLE.COM"},{"objectClassName":"nameserver","ldhName":"NS2.GOOGLE.COM"},{"objectClassName":"nameserver","ldhName":"NS3.GOOGLE.COM"},{"objectClassName":"nameserver","ldhName":"NS4.GOOGLE.COM"}],"rdapConformance":["rdap_level_0","icann_rdap_technical_implementation_guide_0","icann_rdap_response_profile_0"],"notices":[{"title":"Terms of Use","description":["Service subject to Terms of Use."],"links":[{"href":"https:\/\/www.verisign.com\/domain-names\/registration-data-access-protocol\/terms-service\/index.xhtml","type":"text\/html"}]},{"title":"Status Codes","description":["For more information on domain status codes, please visit https:\/\/icann.org\/epp"],"links":[{"href":"https:\/\/icann.org\/epp","type":"text\/html"}]},{"title":"RDDS Inaccuracy Complaint Form","description":["URL of the ICANN RDDS Inaccuracy Complaint Form: https:\/\/icann.org\/wicf"],"links":[{"href":"https:\/\/icann.org\/wicf","type":"text\/html"}]}]}
Sheet Output:

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)
}

Accessing Highrise Data through API using GAS

As the title says, I am having issues accessing data in Highrise through their API using Google Script. I am new to google script, so some of the functions are not entirely clear to me. I understand that for the actual use of the API, I will be using UrlFetchApp.fetch(url) and that the url I will be using is foocompanyname.highrisehq.com/partofhighriseyouwishtoaccess.xml. From there I am lost however. The API documentation explains the process of authentication using curl (something I have never used before) and I cannot think of analogous functions in Google Script to accomplish this.
Here is the curl example they use to simply gain access
curl -u 605b32dd:X https://example.highrisehq.com/people/1.xml
And here is part of the function I am using that is trying to accomplish the same thing. The whole function is designed to obtain all of the notes from the companies visible to the user whose credentials are being used.
function obtainData(){
//enter subject-id of admin
// |
// V
var userid = "123456789"
var payload =
{
"action" : "/companies.xml"
};
var options =
{
"headers" : { "USER-AGENT" : "name#company.com",
"Authorization" : "Basic" + Utilities.base64Encode( "APIkey_from_Highrise_website" + ":" + "Dummy_password" )
},
"method" : "GET",
"payload" : payload,
muteHttpExceptions : true
};
var xmlCompanies = UrlFetchApp.fetch("https://foocompany.highrisehq.com/companies.xml", options).getContentText();
Logger.log(xmlCompanies);
However, when I run this I receive the error "[HTTP Basic: Access denied.
]" which I assume means that I have not passed on the credentials correctly. Could anyone perhaps tell me what I am doing wrong? After this step I am fairly confident about getting the data, it's the authorization that is getting me.
Try this, note the space after "Basic"
function obtainData(){
//enter subject-id of admin
// |
// V
var userid = "123456789"
var payload =
{
"action" : "/companies.xml"
};
var options =
{
"headers" : { "USER-AGENT" : "name#company.com",
"Authorization" : "Basic " + Utilities.base64Encode( "APIkey_from_Highrise_website" + ":" + "Dummy_password" )
},
"method" : "GET",
"payload" : payload,
muteHttpExceptions : true
};
var xmlCompanies = UrlFetchApp.fetch("https://foocompany.highrisehq.com/companies.xml", options).getContentText();
Logger.log(xmlCompanies);

How can I map this WCF functionality to my REST web api?

Greetings I have a WCF service, and basically what the API users do to create a book is following:
var Book = new DtoBook()
{
OpenInModal = false,
CallToActionUrl = "url"
Status = NotificationStatus.Unseen,
TimeStamp = DateTime.Now,
Type = NotificationType.Type,
Message = "test,
};
BookManager.Instance.Add(Book);
I have users to basically do the same thing but instead on the client-side.
I have created a POST method already that looks like this:
public HttpResponseMessage Add(List<DtoBook> Books)
{
if (!ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
BookManager.Instance.Add(Books);
var response = Request.CreateResponse(HttpStatusCode.Created, Books);
return response;
}
So when I enter the url I get following in my console:
{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'test.Controllers.NotificationsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."}
My question is what do I need to do so the user can type the properties of the dToBook class and then the POST happens and the book gets added. I guess right now it just tries to add it without any properties.
Any kind of help is appreciated
Try to specify the method is post, for sample:
[HttpPost]
public HttpResponseMessage Add([FromBody]List<DtoBook> Books)
{
// code
}

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

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.

Categories

Resources