Im trying to use the Channel API of Google App Engine.
JavaScript / JQuery:
$(document).ready(function(){
alert('ready');
$.post('/token', function(data) {
alert('token:' + data['token']);
openChannel( data['token'] );
});
$.post('/chat', function(data) {
alert('chat:' + data['users'].length);
});
});
onMessage = function(message) {
alert(message);
}
onSocketError = function(error){
alert("Error is <br/>"+error.description+" <br /> and HTML code"+error.code);
};
onSocketOpen = function() {
// socket opened
};
onSocketClose = function() {
alert("Socket Connection closed");
};
openChannel = function(token) {
alert('open channel');
var channel = new goog.appengine.Channel( token );
var socket = channel.open();
socket.onopen = onSocketOpen;
socket.onmessage = onMessage;
socket.onerror = onSocketError;
socket.onclose = onSocketClose;
};
The problem is that alert(message) doesn't fire. What is lucking in my code?
Im confused on some of the examples having "\\{\\{ token \\}\\}" in server side and channel = new goog.appengine.Channel('{{ token }}') in javascript.
What is it enclosed in {{ }}?
Please note token is a TOKEN KEY which identifies your page. Initialize token in page first like:
ChannelService channelService = ChannelServiceFactory.getChannelService();
String token = channelService.createChannel("sample");
Now
var token ="<%=token %>";// This will creaete unique identifier(some id created by google api + ur key)
channel = new goog.appengine.Channel('<%=token%>');
socket = channel.open();
socket.onopen = function () {
var connected = true;
sendMessage('<b>'+userName+'</b> Logged in.');
};
.. Create functions like this
Besides using the correct token, your onMessage function doesn't fire because that will happen when you send a message from the server to the client:
channelService.sendMessage(new ChannelMessage(channelKey, "Hello World"));
you can set up a XMLHttpRequest in order to communicate from the client to the server side, where the java code before can be run, for example:
sendMessage = function(path, param) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'path + '&' + param', true);
xhr.send();
};
in javascript
function onMessage(msg)
{
var msg1=msg.data;
$('textarea').val($('textarea').val()+msg1);
}
in backend
ChannelService channelService = ChannelServiceFactory.getChannelService();
channelService.sendMessage(new ChannelMessage(clientid,message));
Related
I'm very new to working with backend server stuff and nodejs. I'm trying to set up Stripe with my app and now trying to create a Connected account with stripe. Was following this https://stripe.com/docs/connect/collect-then-transfer-guide but I don't understand enough to make it work. How do I get information from the server or send it through to make the account.
this is what I got so far
binding.connectWithStripe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String redirect = "https://www.example.com/connect-onboard-redirect";
String url = "https://connect.stripe.com/express/oauth/authorize" +
"?client_id=" + "ca_Hdth53g5sheh4w4hwhw5h4weh5" +
"&state=" + 1234 +
"&redirect_uri=" + redirect;
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(view.getContext(), Uri.parse(url));
}
});
const express = require('express');
const app = express();
app.use(express.json());
const { resolve } = require("path");
const stripe = require('stripe')('sk_test_xxxx');
app.get("/", (req, res) => {
// Display landing page.
const path = resolve("./index.html");
res.sendFile(path);
});
app.get("/connect/oauth", async (req, res) => {
const { code, state } = req.query;
// Assert the state matches the state you provided in the OAuth link (optional).
if(!stateMatches(state)) {
return res.status(403).json({ error: 'Incorrect state parameter: ' + state });
}
// Send the authorization code to Stripe's API.
stripe.oauth.token({
grant_type: 'authorization_code',
code
}).then(
(response) => {
var connected_account_id = response.stripe_user_id;
saveAccountId(connected_account_id);
// Render some HTML or redirect to a different page.
return res.status(200).json({success: true});
},
(err) => {
if (err.type === 'StripeInvalidGrantError') {
return res.status(400).json({error: 'Invalid authorization code: ' + code});
} else {
return res.status(500).json({error: 'An unknown error occurred.'});
}
}
);
});
const stateMatches = (state_parameter) => {
// Load the same state value that you randomly generated for your OAuth link.
const saved_state = 'sv_53124';
return saved_state == state_parameter;
}
const saveAccountId = (id) => {
// Save the connected account ID from the response to your database.
console.log('Connected account ID: ' + id);
}
app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
The sign up page opens and can enter the test info but after submiting it's not actually creating the account in Stripe dashboard. Any help would be much appreciated
enter image description here
After you complete the Express account sign up, Stripe redirects your customer to the redirect URI you specified on your Connect OAuth url (looks like yours is https://www.example.com/connect-onboard-redirect).
You should redirect to a real page of yours here. The redirect URL will append query params containing the authorization code e.g. https://www.example.com/connect-onboard-redirect?code=ac_1234
where ac_1234 is the OAuth authorization code.
You need to parse out that authorization code and send it to your backend and complete the OAuth connection to actually connect that Express account to your Platform: https://stripe.com/docs/connect/oauth-express-accounts#token-request
Got the last piece of my puzzle. Didn't know how to communicate with nodejs and use the GET method. I used volley with this piece of code
RequestQueue queue = Volley.newRequestQueue(getContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://10.0.2.2:4242" + "/connect/oauth",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(">>>>>>>>CONNECTED?", ">>>CONNECTED!!!<<<");
// enjoy your response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(">>>>>>>>>>ERRRRRRROR", error.toString());
// enjoy your error status
}
});
queue.add(stringRequest);
Hope that helps anyone else starting to learn nodejs :)
I am trying to fetch google contacts for a user via oAuth2 mechanism. I am following this tutorial - https://developers.google.com/identity/sign-in/web/server-side-flow
I have javascript code that calls start() on pageload -
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'SOME_CLEINT_ID',
scope: 'https://www.googleapis.com/auth/contacts.readonly'
});
});
}
and
auth2.grantOfflineAccess().then(signInCallback);
and then -
function signInCallback(authResult) {
if (authResult['code']) {
var callback = function(data){
data = JSON.parse(data);
console.log(data);
};
callAjax({action: 'saveGmailAuth', gaccesscode: authResult['code']}, callback, true);
} else {
// There was an error.
}
}
This front end code calls my backend Java web servlet, which tries to get access token -
String authCode = request.getParameter("gaccesscode");
String REDIRECT_URI = "";
String CLIENT_SECRET_FILE = "G:/eclipse_proj/GoogleContacts/CLIENT_JSON_FILE.json";
GoogleClientSecrets clientSecrets;
try {
clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(),
new FileReader(CLIENT_SECRET_FILE));
REDIRECT_URI = clientSecrets.getDetails().getRedirectUris().get(0);
GoogleAuthorizationCodeTokenRequest tokenRequest = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(),
JacksonFactory.getDefaultInstance(), "https://www.googleapis.com/oauth2/v3/token",
clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(), authCode,
REDIRECT_URI);
GoogleTokenResponse tokenResponse = tokenRequest.execute();
String accessToken = tokenResponse.getAccessToken();
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Every time I try this java code, every time it gives me error at tokenRequest.execute() -
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "redirect_uri_mismatch",
"error_description" : "Bad Request"
}
With REDIRECT_URI as empty string, it give another error saying - redirect_uri_not_provided.
I tried it with both "https://www.googleapis.com/oauth2/v3/token" and "https://www.googleapis.com/oauth2/v4/token"
I need help figuring this out. What am I doing wrong here?
My redirect URI is - http://localhost:8080/GoogleContacts/Callback in both json file and in developer console for oauth2.
For redirect_uri in using Google APIs,go to your Google Dev console and type what you see as is:
//you can use any port you want
http:localhost:8080/oauth2callback
oauth2callback is the key ingredient.
I want to store the variable X in a file/DB in server side. Client side is written using AngularJS and server side is using JAVA. The Connection is established using WebSocket.
Now whenever the connection is closing(both when I close it manually and when it closes automatically on some error), I have to send the variable X from AngularJs to JAVA. What is the good way to do that?
Connection establishment - AngularJS code
angular.module('main')
.factory('socket', function ($websocket,$cookies,$state) {
// Open a WebSocket connection
var ws = $websocket("ws://" + document.location.host + "/Server/dialog");
var X = [];
ws.onMessage(function (event) {
console.log('message: ', event.data);
var response;
response = event.data;
X.push({
//some data
});
});
ws.onError(function (event) {
console.log('connection Error', event);
});
ws.onClose(function (event) {
console.log('connection closed', event);
X.push({
//some closing msg
});
//From here I have to send the variable X to the server side
});
ws.onOpen(function () {
console.log('connection open');
ws.send("HELLO");
});
return {
X: X,
status: function () {
return ws.readyState;
},
send: function (message) {
if(message != null){
console.log(message);
X.push({
//some data
});
ws.send(message);
}
}
};
})
How to send the variable while connection is closing?
I am trying to integrate Google Login Button With my Java Application. I am doing like that ...
Controller Side --
#RequestMapping(value = "/lnregister", method = RequestMethod.GET)
public String doLnRegister(#RequestHeader(value = "referer", required = false) final String referer, final RegisterForm form,
final BindingResult bindingResult, final Model model, final HttpServletRequest request,
final HttpServletResponse response, final RedirectAttributes redirectModel) throws CMSItemNotFoundException, IOException
{
response.setContentType("text/html");
final String state = new BigInteger(130, new SecureRandom()).toString(32);
request.getSession().setAttribute("state", state);
response.setContentType("application/json");
final String tokenData = (String) request.getSession().getAttribute("token");
if (tokenData != null)
{
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print(GSON.toJson("Current user is already connected."));
return tokenData;
}
final ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
getContent(request.getInputStream(), resultStream);
final String code = new String(resultStream.toByteArray(), "UTF-8");
try
{
// Upgrade the authorization code into an access and refresh token.
final GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY, CLIENT_ID,
CLIENT_SECRET, code, "postmessage").execute();
// You can read the Google user ID in the ID token.
// This sample does not use the user ID.
final GoogleIdToken idToken = tokenResponse.parseIdToken();
final String gplusId = idToken.getPayload().getSubject();
System.out.print("gplusId >>>>>>>>>>>>>>>>>>>>>>" + gplusId);
// Store the token in the session for later use.
request.getSession().setAttribute("token", tokenResponse.toString());
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print(GSON.toJson("Successfully connected user."));
}
catch (final TokenResponseException e)
{
System.out.println("TokenResponseException :" + e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().print(GSON.toJson("Failed to upgrade the authorization code."));
}
catch (final IOException e)
{
System.out.println("IOException :" + e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().print(GSON.toJson("Failed to read token data from Google. " + e.getMessage()));
}
}
static void getContent(final InputStream inputStream, final ByteArrayOutputStream outputStream) throws IOException
{
// Read the response into a buffered stream
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
int readChar;
while ((readChar = reader.read()) != -1)
{
outputStream.write(readChar);
}
reader.close();
}
And Front side JS --
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
<!-- JavaScript specific to this application that is not related to API
calls -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" ></script>
<div id="gConnect">
<button class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-clientId="*****************"
data-accesstype="offline"
data-callback="onSignInCallback"
data-theme="dark"
data-cookiepolicy="single_host_origin">
</button>
</div>
<div id="authOps" style="display:none">
<h2>User is now signed in to the app using Google+</h2>
<p>If the user chooses to disconnect, the app must delete all stored
information retrieved from Google for the given user.</p>
<button id="disconnect" >Disconnect your Google account from this app</button>
<h2>User's profile information</h2>
<p>This data is retrieved client-side by using the Google JavaScript API
client library.</p>
<div id="profile"></div>
<h2>User's friends that are visible to this app</h2>
<p>This data is retrieved from your server, where your server makes
an authorized HTTP request on the user's behalf.</p>
<p>If your app uses server-side rendering, this is the section you
would change using your server-side templating system.</p>
<div id="visiblePeople"></div>
<h2>Authentication Logs</h2>
<pre id="authResult"></pre>
</div>
<script type="text/javascript">
var helper = (function() {
var authResult = undefined;
return {
/**
* Hides the sign-in button and connects the server-side app after
* the user successfully signs in.
*
* #param {Object} authResult An Object which contains the access token and
* other authentication information.
*/
onSignInCallback: function(authResult) {
$('#authResult').html('Auth Result:<br/>');
for (var field in authResult) {
$('#authResult').append(' ' + field + ': ' + authResult[field] + '<br/>');
}
if (authResult['access_token']) {
// The user is signed in
this.authResult = authResult;
helper.connectServer();
// After we load the Google+ API, render the profile data from Google+.
gapi.client.load('plus','v1',this.renderProfile);
} else if (authResult['error']) {
// There was an error, which means the user is not signed in.
// As an example, you can troubleshoot by writing to the console:
console.log('There was an error: ' + authResult['error']);
$('#authResult').append('Logged out');
$('#authOps').hide('slow');
$('#gConnect').show();
}
console.log('authResult', authResult);
},
/**
* Retrieves and renders the authenticated user's Google+ profile.
*/
renderProfile: function() {
var request = gapi.client.plus.people.get( {'userId' : 'me'} );
request.execute( function(profile) {
$('#profile').empty();
if (profile.error) {
$('#profile').append(profile.error);
return;
}
$('#profile').append(
$('<p><img src=\"' + profile.image.url + '\"></p>'));
$('#profile').append(
$('<p>Hello ' + profile.displayName +'!<br />Tagline: ' +
profile.tagline + '<br />About: ' + profile.aboutMe + '</p>'));
if (profile.cover && profile.coverPhoto) {
$('#profile').append(
$('<p><img src=\"' + profile.cover.coverPhoto.url + '\"></p>'));
}
});
$('#authOps').show('slow');
$('#gConnect').hide();
},
/**
* Calls the server endpoint to disconnect the app for the user.
*/
disconnectServer: function() {
// Revoke the server tokens
$.ajax({
type: 'POST',
url: window.location.href + 'disconnect',
async: false,
success: function(result) {
console.log('revoke response: ' + result);
$('#authOps').hide();
$('#profile').empty();
$('#visiblePeople').empty();
$('#authResult').empty();
$('#gConnect').show();
},
error: function(e) {
console.log(e);
}
});
},
/**
* Calls the server endpoint to connect the app for the user. The client
* sends the one-time authorization code to the server and the server
* exchanges the code for its own tokens to use for offline API access.
* For more information, see:
* https://developers.google.com/+/web/signin/server-side-flow
*/
connectServer: function() {
console.log(this.authResult.code);
$.ajax({
type: 'GET',
url: "/store/en/login/lnregister",
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
console.log(result);
helper.people();
},
processData: false,
data: this.authResult.code
});
},
/**
* Calls the server endpoint to get the list of people visible to this app.
*/
people: function() {
$.ajax({
type: 'GET',
url: window.location.href + 'people',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
helper.appendCircled(result);
},
processData: false
});
},
/**
* Displays visible People retrieved from server.
*
* #param {Object} people A list of Google+ Person resources.
*/
appendCircled: function(people) {
$('#visiblePeople').empty();
$('#visiblePeople').append('Number of people visible to this app: ' +
people.totalItems + '<br/>');
for (var personIndex in people.items) {
person = people.items[personIndex];
$('#visiblePeople').append('<img src="' + person.image.url + '">');
}
},
};
})();
/**
* Perform jQuery initialization and check to ensure that you updated your
* client ID.
*/
$(document).ready(function() {
$('#disconnect').click(helper.disconnectServer);
if ($('[data-clientid="YOUR_CLIENT_ID"]').length > 0) {
alert('This sample requires your OAuth credentials (client ID) ' +
'from the Google APIs console:\n' +
'https://code.google.com/apis/console/#:access\n\n' +
'Find and replace YOUR_CLIENT_ID with your client ID and ' +
'YOUR_CLIENT_SECRET with your client secret in the project sources.'
);
}
});
Here When I click on SignIn button, request going to controller but there I am getting TokenResponseException
TokenResponseException :com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_request"
}
I am using profile to get name, image etc, but I am not able to get email_address there.
I tried by getting email-address like profile.email or profile.emailAddress but it is getting undefined.
I am trying to Integrate google login with so many ways, but no getting any luck. Please help.
My Related Post is there.
you need to add email to data-scope
<button class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login email"
i have a jquery cod with me and i want to port it to java. Is there any options available to do this task quickly since i am not familiar with java
Here is my code
ASDR.PostStore = function(ec, options) {
this.ec = ec;
this.target = options && options.target;
var self = this;
var _send = function(url, transaction, pre, post) {
$(transaction).trigger(pre);
$(self).trigger(pre, transaction);
$(self).trigger('sending', transaction);
$.ajax({
type : "POST",
url : url,
data : transaction.toString(),
dataType: "json",
success : function(data) {
ec.expand(data, true);//Always updateOnIntern
$(self).trigger('sent', data);
$(self).trigger(post, data);
$(transaction).trigger(post, data);
},
error : function(data){
console.log("Logging error", data);
}
});
};
this.get = function(transaction) {
var url = (this.target + "get");
_send(url, transaction, 'getting', 'gotten');
}
this.persist = function(transaction) {
var url = (this.target + "persist");
_send(url, transaction, 'persisting', 'persisted');
}
/**
* Always asynchronous.
*/
this.is_async = function(){
return true;
}
}
}
Thanks in advance
Renjith Raj
jQuery is Javascript, which is usually executed on the client side. Java is a program language which is executed on the server side. You cannot directly convert jQuery to Java.
You can however use a library such as GWT which translates Java to Javascript. There is also the possibility to statically render content server side. If you search for JSP/JSTL you'll find many resources.