1.Used the code from this link: Sending email from gmail api not received but shown in sent folder
2. I'm using domino server locally with Domino Designer 9
3. Making sure that I'm able to authorize with Gmail api with my google client id (logout from gmail, run the code which is asking me login again)
The modified version of the above code is not working.
What is wrong in my code or setup.
Here is full code.
// Your Client ID can be retrieved from your project in the Google
// Developer Console, https://console.developers.google.com
// function assignval(cl,sc){
// var CLIENT_ID = '261056497849-8kj87m3pjmqko8iot7kpdee2htmaf29a.apps.googleusercontent.com';
// var CLIENT_ID = cl;
//var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
// var SCOPES = sc;
// }
var CLIENT_ID = '204856067483-0ib90ohcb1itdvho93cf33pc8g83t4lp.apps.googleusercontent.com';
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly','https://mail.google.com/','https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/gmail.compose','https://www.googleapis.com/auth/gmail.send'];
/**
* Check if current user has authorized this application.
*/
function auth() {
var config = {
'client_id': CLIENT_ID,
'scope': SCOPES
};
gapi.auth.authorize(config, function() {
console.log('login complete');
console.log(gapi.auth.getToken());
});
}
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* #param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadGmailApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* #param {Event} event Button click event.
*/
function handleAuthClick(event) {
gapi.auth.authorize(
{client_id: CLIENT_ID, scope: SCOPES, immediate: false},
handleAuthResult);
return false;
}
/**
* Load Gmail API client library. List labels once client library
* is loaded.
*/
function loadGmailApi() {
gapi.client.load('gmail', 'v1',send());
}
function sendMessage(email, callback) {
//auth();
gapi.client.load('gmail', 'v1',function(){
var base64EncodedEmail = btoa(email).replace(/\//g,'_').replace(/\+/g,'-');
alert("Message sending" + base64EncodedEmail);
var request = gapi.client.gmail.users.messages.send({
'userId': 'me',
'message': {
'raw': base64EncodedEmail
}
});
request.execute(callback);
});
}
function send() {
var to = 'mohan_gangan#yahoo.com',
subject = 'Gmail API sendmessage test',
content = 'send a Gmail using domino server'
var email ="From: 'me'\r\n"+
"To: "+ to +"\r\n"+
"Subject: "+subject+"\r\n"+
"\r\n"+
content;
alert("Message sent to Gamil API");
sendMessage(email, function (response) {
//console.log("Handed to Gmail API for sending");
{console.log(response)}
});
alert("Message sent");
}
Related
I'm trying to implement Google Fit, in a school project.
I am using the documentation released by Google but it does not work.
I am getting 403 bad request error
Is it possible because I am using XAMPP to try to connect, it gives me an error?
I have entered the request domains on the Google project.
Can you help me?
Also I have a question:
Does it cost to use Google Fit Api rest?
Thanks everyone for your answers
var CLIENT_SECRET;
var CLIENT_ID;
$.post('healthDataFunc.php', { functionname: 'get_app_credentials' }, function(data){
var result = JSON.parse(data);
if (result){
CLIENT_SECRET = result[0];
CLIENT_ID = result[1];
}
});
var CLIENT_REDIRECT = "https://localdefault.com:4433";
//End-Configuration
var SCOPES_FITNESS = 'https://www.googleapis.com/auth/fitness.activity.read+https://www.googleapis.com/auth/fitness.body.read+https://www.googleapis.com/auth/fitness.location.read+https://www.googleapis.com/auth/fitness.blood_pressure.read+https://www.googleapis.com/auth/fitness.sleep.read';
var GoogleAuth;
/*
Initial request for Google authentication code
Opens google auth window
returns Google Auth token
*/
function requestGoogleoAuthCode() {
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
console.log(gapi);
}
function initClient() {
// In practice, your app can retrieve one or more discovery documents.
var discoveryUrl = "https://www.googleapis.com/discovery/v1/apis/drive/v3/rest";
// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes.
gapi.client.init({
'apiKey': CLIENT_SECRET,
'clientId': CLIENT_ID,
'discoveryDocs': [discoveryUrl],
'scope': SCOPES_FITNESS
}).then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);
// Handle initial sign-in state. (Determine if user is already signed in.)
var user = GoogleAuth.currentUser.get();
GoogleAuth.signIn();
console.log("test--------->", GoogleAuth, user);
});
}
/*
Uses Google Auth code to get Access Token and Refresh Token
returns object with access token, refresh token and access token expiration
*/
function getAccessToken(google_auth_code) {
var retVal = null;
jQuery.ajax({
url: "https://www.googleapis.com/oauth2/v3/token?code=" + google_auth_code + "&redirect_uri=" + CLIENT_REDIRECT + "&client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&scope=&grant_type=authorization_code",
type: "post",
success: function (result) {
console.log("Got Access Token And Refresh Token");
retVal = result;
console.log(result);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Error during getAccessToken");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
retVal = null;
},
async: false
});
return retVal;
}
/*
Uses Refresh token to obtain new access token
returns new access token with expiration
*/
function refreshAccessToken(refresh_token) {
var retVal = null;
jQuery.ajax({
url: "https://www.googleapis.com/oauth2/v3/token?client_secret=" + CLIENT_SECRET + "&grant_type=refresh_token&refresh_token=" + refresh_token + "&client_id=" + CLIENT_ID,
type: "post",
success: function (result) {
console.log("Refreshed Access Token");
retVal = result;
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Error during refreshAccessToken");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
retVal = null;
},
async: false
});
return retVal;
}
function revokeAccess(accessToken) {
GoogleAuth.disconnect();
}
var isAuthorized;
var currentApiRequest;
/**
* Store the request details. Then check to determine whether the user
* has authorized the application.
* - If the user has granted access, make the API request.
* - If the user has not granted access, initiate the sign-in flow.
*/
function sendAuthorizedApiRequest(requestDetails) {
currentApiRequest = requestDetails;
if (isAuthorized) {
// Make API request
// gapi.client.request(requestDetails)
// Reset currentApiRequest variable.
currentApiRequest = {};
} else {
GoogleAuth.signIn();
}
}
/**
* Listener called when user completes auth flow. If the currentApiRequest
* variable is set, then the user was prompted to authorize the application
* before the request executed. In that case, proceed with that API request.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
isAuthorized = true;
if (currentApiRequest) {
sendAuthorizedApiRequest(currentApiRequest);
}
} else {
isAuthorized = false;
}
}
I'm trying to figure out how to use Google's API service, and I have a client and API key for Google OAuth. Specifically, though I want to check a user's organization, and then echo out some info for them. I understand that that info will be visible with a simple CTRL-SHIFT-I or CTRL-U, but that doesn't matter to me right now. Thanks for your help in advance (JavaScript because I want to try to host this on GitHub pages)!
Here's a Google example I've tried, and I just get error 400's (client and API keys have been deleted).
// Enter an API key from the Google API Console:
// https://console.developers.google.com/apis/credentials
var apiKey = 'AIzaSyDyyNLwHpVqy88tRamPt1NbyVWFzYkLuhA';
// Enter the API Discovery Docs that describes the APIs you want to
// access. In this example, we are accessing the People API, so we load
// Discovery Doc found here: https://developers.google.com/people/api/rest/
var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"];
// Enter a client ID for a web application from the Google API Console:
// https://console.developers.google.com/apis/credentials?project=_
// In your API Console project, add a JavaScript origin that corresponds
// to the domain where you will be running the script .apps.googleusercontent.com.
var clientId = '873243932753-jfebiqi1ja0b9a2jiqdiirb8vtjlk4n9.apps.googleusercontent.com.apps.googleusercontent.com';
// Enter one or more authorization scopes. Refer to the documentation for
// the API or https://developers.google.com/people/v1/how-tos/authorizing
// for details.
var scopes = 'profile';
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
function handleClientLoad() {
// Load the API client and auth2 library
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
apiKey: apiKey,
discoveryDocs: discoveryDocs,
clientId: clientId,
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;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
makeApiCall();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.people.people.get({
'resourceName': 'people/me',
'requestMask.includeField': 'person.names'
}).then(function(resp) {
var p = document.createElement('p');
var name = resp.result.names[0].givenName;
p.appendChild(document.createTextNode('Hello, ' + name + '!'));
document.getElementById('content').appendChild(p);
});
}
<p>Say hello using the People API.</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button">Authorize</button>
<button id="signout-button">Sign Out</button>
<div id="content"></div>
<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
Edit: I found out that this needs to be done with Admin SDK. Still a bit confused on how to do this though.
As you mentioned this needs to be done using the Admin sdk API. under the users > get section you can try that API and it will provide you an example about how to use it on JS.
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.user.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("YOUR_API_KEY");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/admin/directory_v1/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.directory.users.get({
"userKey": "<user email address>"
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
});`
Also I recommend you to to use the Quickstart to get more familiar about how to use the Google API's.
I've written some client-side app and tried to test it. How it turned out only I can use it. Anyone else will get such error.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
}
What does it mean? How to solve this?
There is my code. There i'm getting Email, name, surname and user photo. I want to get the number of youtube channel subscribers and work with youtube later. For example I want to rate some videos directly from the site.
function resultFindUserByEmail()
{
if (ajaxRet['isUserFinded'])
{
cf_JSON.clear();
cf_JSON.addItem( 'email',email );
var jsonstr = cf_JSON.make();
ajax_post('doyoutubelogin','loginres','index.php',jsonstr,c_dologin);
}else{
gapi.client.init({
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/people/v1/rest"],
clientId: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES
}).then(function () {
var request = gapi.client.people.people.get({
'resourceName': 'people/me'
}).then(function(response) {
var parsedResponse = JSON.parse(response.body).names;
surname = parsedResponse[0].familyName;
name = parsedResponse[0].givenName;
photo = JSON.parse(response.body).photos[0].url;
addYoutubeUser();
});
});
}
}
function addYoutubeUser() {
cf_JSON.clear();
cf_JSON.addItem( 'Email',email );
cf_JSON.addItem( 'Firstname',name );
cf_JSON.addItem( 'Lastname',surname );
cf_JSON.addItem( 'Image',photo );
var jsonstr = cf_JSON.make();
ajax_post('addyoutubeuser','loginres','index.php',jsonstr,c_dologin);
}
var API_KEY = '<Key removed for posting>';
var API_KEY1='<Key removed for posting>';
var OAUTH2_CLIENT_ID = '<Key removed for posting>';
var OAUTH2_CLIENT_ID1 = '<Key removed for posting>';
var OAUTH2_SCOPES = 'https://www.googleapis.com/auth/youtube.force-ssl';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
var GoogleAuth;
function handleClientLoad() {
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
}
function initClient() {
// Retrieve the discovery document for version 3 of YouTube Data API.
// In practice, your app can retrieve one or more discovery documents.
var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest';
// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes.
gapi.client.init({
'apiKey': API_KEY,
'discoveryDocs': [discoveryUrl,"https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"],
'clientId': OAUTH2_CLIENT_ID,
'scope': OAUTH2_SCOPES
}).then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
//GoogleAuth.grant(OAUTH2_SCOPES);
// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);
// Handle initial sign-in state. (Determine if user is already signed in.)
var user = GoogleAuth.currentUser.get();
setSigninStatus();
// Call handleAuthClick function when user clicks on
// "Sign In/Authorize" button.
$('#sign-in-or-out-button').click(function() {
handleAuthClick();
});
$('#revoke-access-button').click(function() {
revokeAccess();
});
});
}
function handleAuthClick() {
if (GoogleAuth.isSignedIn.get()) {
// User is authorized and has clicked 'Sign out' button.
GoogleAuth.signOut();
} else {
// User is not signed in. Start Google auth flow.
GoogleAuth.signIn();
}
}
function revokeAccess() {
GoogleAuth.disconnect();
}
function setSigninStatus(isSignedIn) {
var user = GoogleAuth.currentUser.get();
var isAuthorized = user.hasGrantedScopes(OAUTH2_SCOPES);
if (isAuthorized) {
$('#sign-in-or-out-button').html('Sign out');
$('#revoke-access-button').css('display', 'inline-block');
$('#auth-status').html('You are currently signed in and have granted ' +
'access to this app.');
//// get gmail Email
gapi.client.init({
'apiKey': API_KEY,
'discoveryDocs': ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"],
'clientId': OAUTH2_CLIENT_ID,
'scope': OAUTH2_SCOPES
}).then(function () {
var request = gapi.client.gmail.users.getProfile({
'userId': 'me'
}).then(function(response) {
email = JSON.parse(response.body).emailAddress;
cf_JSON.clear();
cf_JSON.addItem( 'email',email );
var jsonstr = cf_JSON.make();
tryFindUserByEmail(jsonstr);
});
});
// try to find email
} else {
$('#sign-in-or-out-button').html('Вход через Youtube');
$('#revoke-access-button').css('display', 'none');
$('#auth-status').html('You have not authorized this app or you are ' +
'signed out.');
}
}
function updateSigninStatus(isSignedIn) {
setSigninStatus();
}
How to manage permissions:
When you authenticate a user you are given access to that users account data and only that user. So if you are trying to access data on someone else's account they are not going to have permissions to access it and you are going to get the 403 forbidden error.
Without seeing your code its hard to know what you are doing, but I can guess.
You are using Oauth2 to authenticate users.
You are trying to access something with a hard coded id belonging to your personal account which the user does not have access.
How to fix it will depend on what it is you are trying to do.
You need to check some authentication in the API url like
username , ipaddress , token etc.
Based on the parameter you can control the permission on your API request.for example
http://some/thing?username="testuser"&ipaddress="323.2323.232.32"
You can find the parameters value using the function below
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
And then make you check and implement your error and redirection for specific users.
I guess it will help full for you , Thanks !
code -
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': event
});
request.execute(function(event) {
console.log('Event created: ' + event.htmlLink);
});
and it gives the url as follow
https://content.googleapis.com/calendar/v3/calendars/primary/events?alt=json&key=AIzaSyAqWDNNcpsJNNaZO5Bq8tmiSzvzR1YArAo
I couldn't find the reason. is it something problem in my api key or something else?
Oops! i am very sorry i have found the solution of this problem. Actually the event object that i was sending to calendar was wrong. Now its working fine.it was a silly mistake of mine.This is my total code and it is working fine for me.......
var CLIENT_ID = 'myClientId';
var SCOPES = ["https://www.googleapis.com/auth/calendar"];
var EvntJSn = '';
function addEventInGoogle(eventList){
EvntJSn = eventList;
var apiKey = 'myapikey';
gapi.client.setApiKey(apiKey);
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* #param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult){
if (authResult && !authResult.error) {
loadCalendarApi();
} else {
handleAuthClick(event);
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* #param {Event} event Button click event.
*/
function handleAuthClick(event) {
gapi.auth.authorize(
{
client_id: CLIENT_ID,
scope: SCOPES,
immediate: false
},
handleAuthResult);
return false;
}
function loadCalendarApi() {
gapi.client.load('calendar', 'v3', addEventToGglCalendar);
}
function addEventToGglCalendar(){
var event = EvntJSn;
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': event
});
request.execute(function(event) {
console.log(event);
});
}
I'm creating a service for school email accounts that use Gmail. We don't have access to Google+. I'm using something similar to this sample on Google's docs. It works fine for the most part, but when I login to it with my school account, I get this response in the console:
Object {code: 404, message: "Not Found", data: Array[1], error: Object}
code: 404
data: Array[1]
error: Object
message: "Not Found"
__proto__: Object
How can I authenticate with Google, without using the G+ API?
Thanks!
EDIT: It works perfectly fine with any other account.
Here's the basic Javascript that I've replaced with my own client info.
<script type="text/javascript">
var clientId = '837050751313';
var apiKey = 'AIzaSyAdjHPT5Pb7Nu56WJ_nlrMGOAgUAtKjiPM';
var scopes = 'https://www.googleapis.com/auth/plus.me';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
function makeApiCall() {
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = resp.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(resp.displayName));
document.getElementById('content').appendChild(heading);
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>