I am using Google Contacts API v3 for extracting google contacts.
I'm started with the Google APIs Client Library for JavaScript for authentication and authorization. I have no problems with that part of the API access.
But after doing the auth part I have to fetch the google contacts(read only access would be fine for me). I am using gdata-javascript-client for the Google Contacts API v3.
I am also referring google official doc and have copied the code and made the necessary changes to work for me.
My problem is,
Its not working. Its not entering to the registered call back function.
I have also tried using read only mode. But that too is not working.
There are two pieces of code that I am following, one for editable mode and other is read-only mode.
Editable mode access:
function handleAuthResult(authResult){
if (authResult && !authResult.error) {
fetch_contacts_data(authResult);
};
}
function auth() {
var config = {
'client_id': 'CLIENT_ID',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, handleAuthResult);
}
function fetch_contacts_data(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&max-results=70000&alt=json" + "&callback=?",
dataType: "json",
success:function(data) {
contacts = [];
for (var i = 0, entry; entry = data.feed.entry[i]; i++) {
var contact = {
'name' : entry['title']['$t'],
'id' : entry['id']['$t'],
'emails' : [],
'phoneNumber' : []
};
if (entry['gd$email']) {
var emails = entry['gd$email'];
for (var j = 0, email; email = emails[j]; j++) {
contact['emails'].push(email['address']);
}
}
if (entry['gd$phoneNumber']) {
var phoneNumber = entry['gd$phoneNumber'];
for (var j = 0, phone; phone = phoneNumber[j]; j++) {
contact['phoneNumber'].push(phone['$t']);
}
}
if (!contact['name']) {
contact['name'] = contact['emails'][0] || "<Unknown>";
}
contacts.push(contact);
}
numContacts = contacts.length;
friend_list_json_str = '';
for(var j=0;j<numContacts;j++) {
name = (contacts[j])['name'];
emails = (contacts[j])['emails'];
phone = (contacts[j])['phoneNumber'];
email_list= '';
phone_list= '';
for(var k=0;k<emails.length;k++) {
email_list += '"'+emails[k] + '",' ;
}
email_list = email_list.substring(0, email_list.length -1)
for(var k=0;k<phone.length;k++) {
phone_list = '"'+phone[k] + '",';
}
phone_list += phone_list.substring(0, phone_list.length -1)
friend_json_str = '';
friend_json_str += '{"name":"'+name + '",';
friend_json_str += '"emails":['+email_list+'],';
friend_json_str += '"phoneNumber":['+phone_list+']' ;
friend_json_str += '},';
friend_list_json_str += friend_json_str;
}
friend_list_json_str = friend_list_json_str.substring(0, friend_list_json_str.length - 1);
var user_data = get_user_data();
var len = user_data.length;
user_data = user_data.substring(0, len - 2);
user_data += friend_list_json_str + ']}';
data = "invite_data="+ user_data;
url = '/invite';
var posting = $.post( url, data );
posting.done(function( response_data ) {
});
}
});
}
Read Only access:
function auth() {
var config = {
'client_id': 'CLIENT_ID',
'scope': 'https://www.googleapis.com/auth/contacts.readonly'
};
gapi.auth.authorize(config, handleAuthResult);
}
NOTE: rest of the code is same as above
In both the cases the ajax call is failing,
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&max-results=70000&alt=json" + "&callback=?",
dataType: "json",
success:function(data)
Can someone please tell me why this code is not working?
You're blocked by your browser's popup blocker.
Try to call the auth() method after clicking on a button, it should work.
To void this issue, you need to :
First, attempt a call to gapi.auth.authorize with the parameter {immediate:true}. It will try to obtain a token in background if the user already gave his permission.
If it fails, display a button to the user for authentication. When the user clicks on it, call gapi.auth.authorize with the parameter {immediate:false}.
Related
I keep running to Cannot find function for each in object error while trying to loop entries. Is there something I am not seeing?. Here the code. This code is supposed to fetch time data from a system via API do calculations and send email
function getTime() {
var range = [5323, 9626, 4998];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token'
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + range[i] + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
time_entries.forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
submitted_time_entries.forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
//send mail
}
});
}
}
response.data is probably not the array you expect. The server may be returning an error or a successful response that isn't parseable as an array. To find out, print response.data to the console and confirm it's the array you expect.
Seems my API returned an object. I figured out the way around it by using Object.keys method and it worked. Here is the working code.
function getTime() {
var range = [53, 926, 8098];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token';
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + '449625' + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
Object.keys(time_entries).forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
Object.keys(submitted_time_entries).forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
Logger.log(time_entry)
//send mail
}
});
}
}
I am using a script to get specified contents of specific links on a webpage and it has worked fine before, but after the site changed to https, it has stopped working.
The script is as follows:
var URL = window.location.origin
var episodeLinks = $('table.listing a').map(function(i,el) { return $(el).attr('href'); });
$.ajaxSetup({async:false});
$.getScript("https://kissanime.com/Scripts/asp.js");
var login = "vergo777";
var api_key = "R_6a13f014b38f4f80a31cf7d80a7c18c7";
var long_url;
var startEpisode;
do {
startEpisode = prompt("Enter episode number you want to start from");
if(startEpisode <= 0 || startEpisode > episodeLinks.length) {
alert("Episode number entered must be greater than 0 and lesser than total number of eps");
} else {
break;
}
} while(true);
var endEpisode;
do {
endEpisode = prompt("Enter episode number you want to end at");
if(endEpisode <= 0 || endEpisode > episodeLinks.length || endEpisode < startEpisode) {
alert("Episode number entered must be greater than 0 and lesser than total number of eps");
} else {
break;
}
} while(true);
var videoQuality = prompt("Enter video quality you want to download. Example - '960x720.mp4' (without the quotes)");
var i;
for (i = (episodeLinks.length - startEpisode); i >= (episodeLinks.length - endEpisode); i--) {
jQuery.ajax({
url: URL + episodeLinks[i],
success: function(result) {
var $result = eval($(result));
var stringStart = result.search("var wra");
var stringEnd = result.search("document.write");
var javascriptToExecute = result.substring(stringStart, stringEnd);
eval(javascriptToExecute);
$("body").append('<div id="episode' + i + '" style="display: none;"></div>')
$('#episode' + i).append(wra);
var downloadQualityOptions = $('#episode' + i + ' a').map(function(i,el) { return $(el); });
var j;
for(j = 0; j < downloadQualityOptions.length; j++) {
if(videoQuality === downloadQualityOptions[j].html()) {
long_url = downloadQualityOptions[j].attr('href');
console.log(i);
get_short_url(long_url, login, api_key);
}
}
},
async: false,
script: true
});
}
function get_short_url(long_url, login, api_key)
{
$.getJSON(
"http://api.bitly.com/v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url,
async: true
},
function(response)
{
console.log(response.data.url);
}
);
}
I am getting the error: Uncaught ReferenceError: asp is not defined(…)
Any help is very appreciated, thank you!
I have a file called parsing.html that parses through a xml feed and converts the metadata into JSON Object called "data". I'm trying to output this JSON "data" as a JSON feed such as http://www.videws.com/gtv/videosources.php. Is doing
document.write(JSON.stringify(data)) the equivalent of creating a JSON feed in this case?
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
//document.write(categories);
category.videos.push(video);
}
data.categories.push(category);
}
});
document.write(JSON.stringify(data));
}
})
im not sure you fully understand what http://www.videws.com/gtv/videosources.php is doing.
if you look at the source code it appears not to have any javascript at all so its not doing a document.write, it is more likely doing all of the conversion to JSON within PHP server side then streaming out.
a good help site for using PHP with JSON is available here: http://www.tutorialspoint.com/json/json_php_example.htm
i would say that if your more of a JS/HTML guru you may get more out of NODEJS than PHP but that's entirely up to you.
I want to be able to calculate and display on my contact form the most recent Actual End date of that contacts appointments.
The following query shows how I have achieved the same functionality against the Account Entity.
How to test what data is present in d.data.results when querying CRM 2011 AppointmentSet using JavaScript and REST OData
Now I have tried to do the same on contacts but regardingobjectid does not match against any contacts. So I'm asking how do I go about this.
Do I need to open and expand each partylist for the Organiser, Optional Attendees and Required Attendees? If so How would I go about creating the query for this? Using the $expand functionality?
Please help a troubled mind!
Bump!
Ok so I have been working on this issue for a few days now.
I found that it was possible to complete this task with the help of the following tool XRM Dynamics Tools to help generate my OData query code.
Essentially the problem I had was understanding how contacts were linked to the Appointment. Once I understood that all participants for an appointment would be contained in the "appointment_activity_parties" field of an Appointment I was able to see how to create a suitable query to handle this problem.
By choosing the activityid, actualEnd fields and using the expand functionality on the appointment_activity_parties, selecting the PartyId from this expanded field enabled me to check that the party type was a contact, that the contactId of the Party matched with the current contact we were viewing. This way I could count the total number of matches and record the most recent date of a completed appointment for that contact.
In the end I also broke the problem down into 2 queries. One for each year: current and previous. I added three new fields to the Contact form. Two that hold the integers for VisitsLastYear and VisitsThisYear and a lookup to hold a link to the Appointment as can be seen in the following screenshot:
My code follows:
/// <reference path="XrmPageTemplate.js" />
/// <reference path="JQuery.js" />
/// <reference path="SDK.REST.js" />
/// <reference path="json2.js" />
function HarrionAB_ContactForm_OnLoad() {
// get the contact id from the page
var contactId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "")
// if we got a value
if (contactId != "") {
var currentYear = new Date().getFullYear();
var query = "/AppointmentSet?"; // Appointments table
query += "$select=ActualEnd,ActivityId,appointment_activity_parties/PartyId"; // Select
query += "&$expand=appointment_activity_parties"; // Expand sub tables
query += "&$filter=ActivityTypeCode eq 'appointment' and StateCode/Value eq 1 and "; // Where
CountVisitsThisYear(query, currentYear);
CountVisitsLastYear(query, currentYear - 1);
}
}
function CountVisitsThisYear(query, currentYear) {
var start = currentYear.toString() + "-01-01T00:00:00";
var end = currentYear.toString() + "-12-31T00:00:00";
query += "ActualStart ge datetime'" + start + "' or ActualStart le datetime'" + start + "' and "; // Where
query += "ActualEnd ge datetime'" + end + "' or ActualEnd le datetime'" + end + "'"; // Where
// call function to execute the odata query
ExecuteVisitsThisYearQuery(query);
}
function CountVisitsLastYear(query, lastYear) {
var start = lastYear.toString() + "-01-01T00:00:00";
var end = lastYear.toString() + "-12-31T00:00:00";
query += "ActualStart ge datetime'" + start + "' or ActualStart le datetime'" + start + "' and "; // Where
query += "ActualEnd ge datetime'" + end + "' or ActualEnd le datetime'" + end + "'"; // Where
// call function to execute the odata query
ExecuteVisitsLastYearQuery(query);
}
//
// ExecuteQuery executes the specified OData Query asyncronously
//
// NOTE: Requires JSON and jQuery libraries. Review this Microsoft MSDN article before
// using this script http://msdn.microsoft.com/en-us/library/gg328025.aspx
//
function ExecuteVisitsThisYearQuery(ODataQuery) {
// get the server url
var serverUrl = Xrm.Page.context.getServerUrl();
// Adjust URL for differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//
// Handle result from successful execution
//
// e.g. data.d.results
var contactId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");
var lastVisitDate;
var activityId;
var count = 0;
// if we have results
if (data.d.results.length > 0) {
// loop through the appointment results
for (i = 0; i < data.d.results.length; i++) {
// if we have results
if (data.d.results[i].appointment_activity_parties.results.length > 0) {
// loop through the appointment_activity_parties
for (j = 0; j < data.d.results[i].appointment_activity_parties.results.length; j++) {
// if the party id type is contact and the contact ids match
if (data.d.results[i].appointment_activity_parties.results[j].PartyId.LogicalName == "contact" && contactId.toLowerCase() == data.d.results[i].appointment_activity_parties.results[j].PartyId.Id.toLowerCase()) {
// if we have not got a date yet
if (lastVisitDate == null) {
// set the date as this is the first date we found
lastVisitDate = data.d.results[i].ActualEnd;
activityId = data.d.results[i].ActivityId;
} else {
// if the current date is < new date
if (lastVisitDate < data.d.results[i].ActualEnd) {
// reset the date as we have found a later one
lastVisitDate = data.d.results[i].ActualEnd;
activityId = data.d.results[i].ActivityId;
}
}
++count;
}
}
}
}
}
Xrm.Page.getAttribute("new_visitsthisyear").setValue(count);
// if we found a completed appointment
if (count > 0) {
SetLookup("new_lastvisitcompleted", activityId, ParseJsonDate(lastVisitDate).toString('dd/MM/yyyy'), "Appointment");
}
},
error: function (XmlHttpRequest, textStatus, errorObject) {
//
// Handle result from unsuccessful execution
//
alert("OData Execution Error Occurred");
}
});
}
//
// ExecuteQuery executes the specified OData Query asyncronously
//
// NOTE: Requires JSON and jQuery libraries. Review this Microsoft MSDN article before
// using this script http://msdn.microsoft.com/en-us/library/gg328025.aspx
//
function ExecuteVisitsLastYearQuery(ODataQuery) {
// get the server url
var serverUrl = Xrm.Page.context.getServerUrl();
// Adjust URL for differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//
// Handle result from successful execution
//
// e.g. data.d.results
var contactId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");
var count = 0;
// if we have results
if (data.d.results.length > 0) {
// loop through the appointment results
for (i = 0; i < data.d.results.length; i++) {
// if we have results
if (data.d.results[i].appointment_activity_parties.results.length > 0) {
// loop through the appointment_activity_parties
for (j = 0; j < data.d.results[i].appointment_activity_parties.results.length; j++) {
// if the party id type is contact and the contact ids match
if (data.d.results[i].appointment_activity_parties.results[j].PartyId.LogicalName == "contact" && contactId.toLowerCase() == data.d.results[i].appointment_activity_parties.results[j].PartyId.Id.toLowerCase()) {
++count;
}
}
}
}
}
Xrm.Page.getAttribute("new_visitslastyear").setValue(count);
},
error: function (XmlHttpRequest, textStatus, errorObject) {
//
// Handle result from unsuccessful execution
//
alert("OData Execution Error Occurred");
}
});
}
// function to parse JSON date into JavaScript Date
function ParseJsonDate(jsonDate) {
var offset = new Date().getTimezoneOffset() * 60000;
var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);
if (parts[2] == undefined)
parts[2] = 0;
if (parts[3] == undefined)
parts[3] = 0;
return new Date(+parts[1] + offset + parts[2] * 3600000 + parts[3] * 60000);
};
//function to create a lookup control
function SetLookup(fieldName, idValue, textValue, typeValue) {
var value = new Array();
value[0] = new Object();
value[0].id = idValue;
value[0].name = textValue;
value[0].typename = typeValue;
Xrm.Page.getAttribute(fieldName).setValue(value);
}
//
// Error Handler
//
function ErrorHandler(XMLHttpRequest, textStatus, errorObject)
{ alert("Error Occurred : " + textStatus + ": " + JSON.parse(XMLHttpRequest.responseText).error.message.value); }
Hope this helps anyone with similar issues.
I'm trying to implement Login through LinkedIn using the following link Login through LinkedIn
.
Below is my code`
var oauth_info = {};
var consumer_key = "";
var shared_secret = "";
var oauth = OAuthSimple(consumer_key, shared_secret);
function parse_response(response) {
response.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { oauth_info[$1] = $3; });
console.log("oauth_token1="+oauth_info.oauth_token);
}
function linkedInLogin()
{
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/requestToken", parameters: {oauth_callback: "http://www.example.com/"}}).signed_url;
console.log("url==="+url);
$.ajax(
{
url:url,
data: {},
success: function(data){
console.log("inside success");
console.log("response==="+data);
parse_response(data);
console.log("oauth_token2="+oauth_info.oauth_token);
var params = data;
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_token') {
localStorage.oauth_token = y[1];
console.log("oauth_token=="+localStorage.oauth_token);
}
if(y[0]==='oauth_token_secret')
{
localStorage.oauth_token_secret=y[1];
console.log("oauth_token_secret=="+localStorage.oauth_token_secret);
}
}
step2();
},
error: function(error) {
console.log("error");
client_browser.close();
},
dataType: 'text',
type: 'GET'
});
}
function step2()
{
var authoriseurl='https://www.linkedin.com/uas/oauth/authenticate?oauth_token='+oauth_info.oauth_token+'';
window.plugins.childBrowser.showWebPage(authoriseurl);
window.plugins.childBrowser.onLocationChange = function(loc){
console.log("on loc changed");
linkedInChanged(loc);
};
}
function linkedInChanged(loc)
{
console.log("inside loc changed");
if (loc.indexOf("http://www.example.com/") > -1) {
window.plugins.childBrowser.close();
console.log("oauth_token3="+oauth_info.oauth_token);
var index, verifier = '';
var params = loc.substr(loc.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
console.log("verifier===="+verifier);
}
}
var acces_url= access_token_url(verifier);
oauth.reset();
console.log("oauth_token4="+oauth_info.oauth_token);
//console.log("oauth_info"+oauth_info[0][0]+"===="+oauth_info[0][1]);
//var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {oauth_verifier: verifier}, signatures: oauth_info}).signed_url;
console.log("access _url="+acces_url);
$.ajax(
{
url:acces_url,
data: {},
success: function(data){
console.log("inside access token success");
console.log("response==="+data);
var params = data;
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_token') {
localStorage.linkedIn_access_Token = y[1];
console.log("linkedIn_access_Token=="+localStorage.linkedIn_access_Token);
}
if(y[0]==='oauth_token_secret')
{
localStorage.linkedIn_access_secret=y[1];
console.log("linkedIn_access_secret=="+localStorage.linkedIn_access_secret);
}
}
},
error: function(error){
console.log("error=="+error.responseText);
},
dataType: 'text',
type: 'GET'
});
}
}
function get_url_vars_from_string(url) {
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function access_token_url(pin) {
oauth.reset();
//alert(oauth_info.oauth_token);
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {oauth_verifier: pin}, signatures: oauth_info}).signed_url;
// alert("url="+url);
return url;
}
`
On click of a button the linkedInLogin method is called.
I'm not able to get the access token from this code.The ajax call for access token results in Error oauth_problem=token_rejected
Please help
I had the same problem, and found out where the issue comes from.
So, I've come to the request for the accessToken, and have to generate the signature. When I call OAuth.completeRequest() - this is where the signature gets generated - I pass two parameters, and the second one is an object that contains four things (the first two are application settings and next two are from my first request, for the request token):
The api key.
The api secret.
The request token.
The request token secret.
The fourth one was missing on my end. That was the problem.
Also - I'm using this OAuth library - http://oauth.googlecode.com/svn/code/javascript/oauth.js, so the methods/functions on your end could have completely different name. But you've got the idea.
Hope this helps ;)