Fetching salesforce data via gmail gadget - javascript

I am trying to fetch salesforce records in Gmail using OAuth. I am reading about Contextual Gadgets but am not able to get the OAuth request triggered.
I am able to see all my javascript alerts but the popup for authorization does not come up.
Any help/tips are appreciated.
Please find below the code for reference:
<?xml version="1.0" encoding="UTF-8"?>
<Module>
<ModulePrefs title="SF OAuth">
<Require feature="dynamic-height"/>
<Require feature="google.contentmatch">
<Param name="extractors">
google.com:SenderEmailExtractor
</Param>
</Require>
</ModulePrefs>
<Content type="html" view="card">
<![CDATA[
<!-- Start with Single Sign-On -->
<script type="text/javascript" src="https://gist.github.com/Sujit1987/7672590/raw/86a330515eede7c169280718decc9de4ddb494fb/jquery.js"></script>
<script type="text/javascript" src="https://gist.github.com/Sujit1987/7673430/raw/7e066e610cf98a16769c93f733efedb13fa4a5b5/jquery.popup.js"></script>
<script type="text/javascript" src="https://gist.github.com/Sujit1987/7671399/raw/f175870455f7dfe41a3dffeef7ae605138810619/forcetk.js"></script>
<script type="text/javascript">
// OAuth Configuration
var loginUrl = 'https://login.salesforce.com/';
var clientId = '******';
var redirectUri = 'https://gist.github.com/Sujit1987/7672925/raw/72a98f5a5cae641b20ad36841448f4edee6ec601/oauthcallback.html';
var proxyUrl = 'https://gist.github.com/Sujit1987/7671408/raw/ae3d9059a9fb032e0e231a8c54f00f076059f736/proxy.php?mode=native';
var client = new forcetk.Client(clientId, loginUrl, proxyUrl);
$(document).ready(function() {
alert('Hello - Inside Ready function');
$('#message').popupWindow({
windowURL: getAuthorizeUrl(loginUrl, clientId, redirectUri),
windowName: 'Connect',
centerBrowser: 1,
height:524,
width:675
});
$('#message').show();
alert('Hello - Exiting Ready Function');
});
function getAuthorizeUrl(loginUrl, clientId, redirectUri){
alert('Get Authorized Called'+loginUrl+'services/oauth2/authorize?display=popup'
+'&response_type=token&client_id='+escape(clientId)
+'&redirect_uri='+escape(redirectUri));
return loginUrl+'services/oauth2/authorize?display=popup'
+'&response_type=token&client_id='+escape(clientId)
+'&redirect_uri='+escape(redirectUri);
}
function sessionCallback(oauthResponse) {
alert('Hello - Session Call Back');
if (typeof oauthResponse === 'undefined'
|| typeof oauthResponse['access_token'] === 'undefined') {
$('#message').html('Error - unauthorized!');
} else {
client.setSessionToken(oauthResponse.access_token, null,
oauthResponse.instance_url);
client.query("SELECT Name FROM Account LIMIT 1",
function(response){
$('#message').html('The first account I see is '
+response.records[0].Name);
});
}
}
var clients = [];
matches = google.contentmatch.getContentMatches();
for(var match in matches)
{
for(var key in matches[match])
{
if(key == 'sender_email')
{
clients.push(matches[match][key]);
}
}
}
/*gadgets.window.adjustHeight(100);*/
/*function showEmail(){
document.write(clients);
}*/
</script>
<form>
<!-- <button type="button" onclick="showEmail();"> Show Sender Email </button>
<button type = "button" onclick ="getAuthorizeUrl();"> Query SalesForce </button> -->
<p id="message">Click here.</p>
</form>
]]>
</Content>
</Module>

Related

TypeError: gapi.client is undefined error while downloading files from file picker

I have implemented a google file picker in HTML and JS. I have created a client credentials and in the verge of downloading the files from file picker. My code is
<!DOTYPE html>
<html>
<head>
<title>My website</title>
<script type="text/javascript">
// The Browser API key obtained from the Google API Console.
var developerKey = '############################';
// The Client ID obtained from the Google API Console. Replace with your own Client ID.
var clientId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
// Scope to use to access user's photos.
var scope = 'https://www.googleapis.com/auth/drive';
var appId = "1255s8a2s";
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth2', onAuthApiLoad);
gapi.load('picker', onPickerApiLoad);
gapi.client.load('drive', 'v2',handleClientLoad);
}
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(onAuthApiLoad,1);
}
function onAuthApiLoad() {
var authBtn = document.getElementById('auth');
authBtn.disabled = false;
authBtn.addEventListener('click', function() {
gapi.auth2.authorize({
client_id: clientId,
scope: scope
}, handleAuthResult);
});
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes("image/png,image/jpeg,image/jpg");
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.NAV_HIDDEN).
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
setOAuthToken(oauthToken).
setAppId(appId).
addView(view).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
var ids=[];
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var ln = data[google.picker.Response.DOCUMENTS];
for(i=0;i<ln.length;i++) {
ids[i] = data.docs[i].id;
gapi.client.drive.files.get({'fileId': ids[1]});
}
}
}
</script>
</head>
<body>
<h1> Welcome to detect the colours of your image </h1>
<p> Please upload required images. Let us detect what wonderful colours do your images have</p>
<form id="upload-form" action="{{ url_for('upload') }}" method = "POST" enctype="multipart/form-data">
<input type = "file" name="file" accept="image/*" multiple>
<input type="submit" value="upload">
</form>
<form method = "POST" action="/gdrive">
<button type="button" id="auth">upload from google</button>
</form>
<div id="result"></div>
<!-- The Google API Loader script. -->
<script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script>
</body>
</html>
After reading google drive javascript api gapi.client.drive.files undefined, I decided to add gapi.client.load('drive', 'v2', callback); in my code. However the result remains the same. I could not initialize the gapi.client, The drive api is enabled. I am new to Javascript, Can anyone please help me download the files using file ids. The File ids are stored in ids[] array in the code.
Thank you for trying to help me out

Google Contacts to Dropdown List

I'm wondering if anyone can help with this. I am using the following code to pull my google contacts using OAuth and it's working fine so far, I get a response in the console log with XML from google that seems very complicated to read to be honest.
My end goal is to be able to populate a HTML form drop down list with the names of contacts from my address book, and attribute the phone number for that contact as a value for the chosen name.
Here's the code, please let me know if you have any ideas!
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
var clientId = 'ID_HERE';
var apiKey = 'KEY_HERE';
var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
$(document).on("click",".googleContactsButton", function(){
gapi.client.setApiKey(apiKey);
window.setTimeout(authorize);
});
function authorize() {
gapi.auth.authorize(
{
client_id: clientId,
scope: scopes,
immediate: false
},
handleAuthorization
);
}
function handleAuthorization(authorizationResult) {
if (authorizationResult && !authorizationResult.error) {
$.get(
"https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token="
+ authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
//process the response here
console.log(response);
}
);
}
}
</script>
<script src="https://apis.google.com/js/client.js"></script>
<button class="googleContactsButton">Get my contacts</button>
</body>
</html>
EDIT
So, I've played around for a bit, and this is what I've got so far, which works fine, I get the results listed in as name on one line, then number on the next, then name, and so on..
Problems so far are as follows.
This only returns a limited number of contacts, I believe there's a limit on the response from the API which is 200 or something (I think), how would I go about having it display ALL the contacts that are there?
Also I'm still trying to get it to display in a select box format, allowing me to choose a name, and it would pass the number linked to that name to the form.
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>People API Quickstart</title>
<meta charset='utf-8' />
</head>
<body>
<p>People API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = 'CLIENT ID.apps.googleusercontent.com';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/people/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/contacts.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listConnectionNames();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the display name if available for 10 connections.
*/
function listConnectionNames() {
gapi.client.people.people.connections.list({
'resourceName': 'people/me',
'pageSize': 2000,
'personFields': 'names,phoneNumbers',
}).then(function(response) {
console.log(response)
var connections = response.result.connections;
appendPre('<select>');
if (connections.length > 0) {
for (i = 0; i < connections.length; i++) {
var person = connections[i];
if (person.names && person.names.length > 0) {
appendPre(person.names[0].displayName)
appendPre(person.phoneNumbers[0].value)
} else {
appendPre("No display name found for connection.");
}
}
} else {
appendPre('No upcoming events found.');
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
Accessing the Contacts
When you receive the response, the contacts are located under response.feed.entry, which is an array of contacts. Let's save those under var contacts = response.feed.entry. And as an example for what follows, let's take the contact Jimmy : var jimmy = contacts[0].
You have several attributes that you can access, like :
Email : jimmy.gd$email[0].address. ( there can be more emails )
Name : jimmy.title.$t.
Phone : jimmy.gd$phoneNumber[0].$t.
Address : jimmy.gd$postalAddress[0].$t.
Last update made : jimmy.updated.$t.
Warning : If the field is not set, it will be undefined. You have to first verify that it exists, like so :
// Standard way
var name;
if (jimmy.title != undefined) name = jimmy.title.$t
else name = "?? well too bad ??";
// The ninja way
var name = jimmy.title ? jimmy.title.$t : null;
Also
Change your get url to https://www.google.com/m8/feeds/contacts/default/**full**/... as you will get more information on your contacts.
Populating a drop-down
For simplicity, you could use a <select> tag and insert the contacts as <option> tags in it. Else, you can also use libraries like bootstrap that has cool drop-downs menus.
If your code still doesn't work...
Try this code :
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
function auth() {
var config = {
'client_id': 'OAUTH_CLIENT_ID',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full?alt=json',
dataType: 'jsonp',
data: token
}).done(function(data) {
console.log(JSON.stringify(data));
});
}
</script>
</head>
<body>
<button onclick="auth();">GET CONTACTS FEED</button>
</body>
</html>
Source

HTTP Error 405.0 - Method Not Allowed while accessing web-api from angularjs app

I am creating a anjular js app where i have created a login page and i m authenticating it using web api. This is the controller which is returning json and it is running properly.
[Route("api/Customer/{id}/{pass}")]
public IEnumerable GetCustomer(string id, string pass)
{
var list = repository.Get(id, pass);
if (list != null)
{
return list;
}
else
{
return null;
}
}
this is the controller accessing the api in angular app (demoApi.js)
(function () {
'use strict';
var DemoApi = function ($http) {
var loginCheck = function (username, password) {
return $http.get("http://localhost:8115/api/Customer/" +username+"/"+password)
.then(function (response) {
return response.data;
});
};
return {
loginCheck: loginCheck
}
};
var app = angular.module("angularApp");
app.factory("DemoApi", DemoApi);
}());
this is the login controller(loginController.js)
(function () {
var app = angular.module("angularApp");
var loginController = function ($scope, $http, bankApi, $location) {
var userDetails = {
username: $scope.uName,
password: $scope.uPassword
};
$scope.login = function () {
DemoApi.loginCheck(userDetails.username, userDetails.password)
.then(onLogin, onError);
};
var onError = function (reason) {
$scope.error = "Could not fetch the data.";
};
var onLogin = function (data) {
$scope.details = data;
$location.path("/info");
};
}
app.controller('loginController', loginController);
}());
this is the index page where i have all the scripts linked
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="angularApp">
<head>
<title>Ebank</title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-route.js"></script>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="lib/app.js"></script>
<script src="lib/bankApi.js"></script>
<script src="lib/loginController.js"></script>
<script src="lib/infoController.js"></script>
</head>
<body style="background-color:#333">
<div ng-view></div>
</body>
</html>
Provide me with a solution, why i m not able to call api from demoApi.js
I'm getting the response if i call this api directly from the html page but not getting response from demoApi.js
Most probably you bumped into CORS issue. You need to enable CORS. Follow below mentioned steps.
Open IISExpress config file applicationhost.config located at C:\Program Files (x86)\IIS Express\AppServer.
Search for "httpProtocol" tag. Inside it check if "customHeaders" tag exists. If not then add it.
Add following two tag inside "customHeaders" tag.
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
Alternatively you can run chorme browser in security disabled mode using following command on command prompt and try accessing your site from there.
Full path to chrome.exe --disable-web-security --user-data-dir
Note its just workaround to test your application however in production deployment you need to enable CORS.

How to Login with linkedin using javascript and display profile information

I want to integrate Linkedin login using javascript.
I searched for that and get relevant results. But lot of search results says that below code:
<script type="in/Login">
</script>
is used to create sign-in button. But i want to use my own custom button and call a function on "onClick" event in my HTML.
Help in correct direction.
My code :
function linkedinLogin(){
console.log('linkedinLogin called');
var src="http://platform.linkedin.com/in.js"
api_key: 'XXXXXXXXXXXXXXXX'
authorize: true
onLoad: OnLinkedInFrameworkLoad
}
function OnLinkedInFrameworkLoad()
{
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles)
{
var member = profiles.values[0];
console.log(member);
var id=member.id;
var firstName=member.firstName;
var lastName=member.lastName;
var photo=member.pictureUrl;
var headline=member.headline;
//use information captured above
var str="<b>id</b> : "+id+"<br>";
str +="<b>firstName: </b>"+firstName+"<br>";
str +="<b>lastName: </b>"+lastName+"<br>";
str +="<b>photo: </b>"+photo+"<br>";
str +="<b>headline: </b>"+headline+"<br>";
str +="<input type='button' value='Logout' onclick='logout();'/>";
document.getElementById("status").innerHTML = str;
}
And this is my HTML snippet:
<li>
<a href="javascript:void(0);" onClick="linkedinLogin()">
<img src="images/icon_linkedIn.png" />
<span>LinkedIn</span>
</a>
</li>
<html>
<head>
<title>LinkedIn JavaScript API Hello World</title>
<!-- 1. Include the LinkedIn JavaScript API and define a onLoad callback function -->
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: xxx
onLoad: onLinkedInLoad
authorize: true
</script>
<script type="text/javascript">
// 2. Runs when the JavaScript framework is loaded
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
// 2. Runs when the viewer has authenticated
function onLinkedInAuth() {
IN.API.Profile("me").fields("id","first-name", "last-name", "email-address").result(displayProfiles);
}
// 2. Runs when the Profile() API call returns successfully
function displayProfiles(profiles) {
member = profiles.values[0];
document.getElementById("profiles").innerHTML =
"<p>"+member.id+"<br> " + member.firstName + "<br> " + member.lastName + "<br>"+member.emailAddress+"</p>";
}
</script>
</head>
<body>
<!-- 3. Displays a button to let the viewer authenticate -->
<script type="in/Login"></script>
<!-- 4. Placeholder for the greeting -->
<div id="profiles"></div>
</body>
</html>
Can you try this ?

Transferring file from Google to Parse.com

I have created a system where user selects files from their Google drive to be uploaded into Parse.
I have done so separately though, where I have one code that allows user to select an item from Google drive, and one that allows user to upload a file from their computer into parse.
Google drive (Using Google drive picker):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>eSnail Scan Upload Part 2</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'KEY';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
}
</script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
That allows a user to upload a file into Parse (PDF):
<HTML>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// ***************************************************
// NOTE: Replace the following your own keys
// ***************************************************
Parse.initialize("ID", "ID");
function saveDocumentUpload(objParseFile)
{
var documentUpload = new Parse.Object("Scan");
documentUpload.set("Name", "");
documentUpload.set("DocumentName", objParseFile);
documentUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
$('#myForm').bind("submit", function (e) {
e.preventDefault();
var fileUploadControl = $("#documentFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
var user_id = $('#user_id').val();
var address = $('#address').val();
parseFile.set('UserId', user_id);
parseFile.set('Address', address);
parseFile.save().then(
function () {
saveDocumentUpload(parseFile);
},
function (error) {
alert("error");
}
);
});
});
</script>
<body><form id='myForm'>
<input type="file" id="documentFileUpload">
<br/>
<input type="text" placeholder="UserID" id="user_id">
<br/>
<input type="text" placeholder="Address" id="address">
<br/>
<input type="submit" value="submit">
</form>
</body>
</HTML>

Categories

Resources