Google Play services leaderboard sample scripts are not running - javascript

I am trying to implement Google Leaderboard for my games.
So I have downloaded sample scripts from the following URL: https://github.com/playgameservices/web-basic-samples
and put it in the web server:
E:\wamp\www\sugumar\web-basic-samples-master
and in the browser I tried
http://localhost/sugumar/web-basic-samples-master/type-a-number-js/index.html
but it showed the following error
Not Found
The requested URL
/sugumar/web-basic-samples-master/type-a-number-js/index.html was not
found on this server.
so I checked the file permissions for the folder web-basic-samples-master (I have so many projects running under sugumar folder so no problem with that folder permission).
It was in read only mode, so I unchecked the readonly and clicked on apply and on the next screen I clicked ok for "Apply changes to this folder, subfolders files" and then I clicked on ok, and then run the following url again
http://localhost/sugumar/web-basic-samples-master/type-a-number-js/index.html
but it still shows the same problem:
Not Found
The requested URL
/sugumar/web-basic-samples-master/type-a-number-js/index.html was not
found on this server.

It seems you've skipped the entire Running the sample application guide accompanying the code sample:
To run this sample application in your own environment, perform the
following steps:
1.Get the latest Google APIs Client Library for PHP and extract it into your server directory.
- We recommend you retrieve this using git, to ensure you always have the latest version. (e.g. git clone
https://github.com/google/google-api-php-client)
- Alternately, you can get the gzip file from the downloads page. Please make sure you download version 0.6.2 or later (updated June 3,
2013), as the GameService contrib file does not exist in earlier
versions.
2.This application assumes you have PHP/MySQL already running on your server. Create a users table with the following setup:
CREATE TABLE IF NOT EXISTS `users` ( `temp_key` varchar(128) NOT
> NULL, `user_id` varchar(64) NOT NULL, `bearer_token`
> varchar(1024) NOT NULL, `last_modified` timestamp NOT NULL DEFAULT
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY
> (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Create your own application in the Play Console, as described in the Create Client IDs portion of the documentation. Make sure you
follow the "Web" instructions for creating your Client ID and linking
your application.
If you've already set up your own version of the Type-a-Number sample
application, you can repurpose that application here. Either create a
new linked application (which will give you a new client ID), or add
your test server to your list of Javascript Origins in the APIs
Console (which will let you re-use your current client ID)
When you link your Web application, ensure the hostname matches the server from which you'll be testing your application. (e.g.
http://localhost/ or https://www.mytestserver.com). Also, make sure
that you have the right protocol (http vs. https)
Make a note of your Client ID and Client Secret as described in the documentation
Create a Leaderboard as described in the Leaderbords documentation. Give it a creative name like "High scores".
Once that's done, you'll want to replace the following constants defined in the SampleAppConstants.ini file.
In the api section, replace the following: clientId (Replace this with
your OAuth2.0 Client ID) clientSecret (Replace this with your OAuth2.0
Client secret) In the db section, replace the following: user (Replace
this with your MySQL username) pass (Replace this with your MySQL
password) host (Replace this with your MySQL hostname) name (Replace
this with the name of the MySQL database you're using.) In the game
section, replace the following: leaderboardId (Replace this with the
ID of the leaderboard you created in the previous step.)
Move your AppConstants.ini file outside of your htdocs tree. This contains sensitive information and it shouldn't be located anywhere
where it could accidentally be displayed to the user.
Update the constructor in your GameHandler file to point to the new location of AppConstants.ini.
That's it! Your application should be ready to run!

Related

Shopify wishlist app - displaying item information from products.json?

I'm trying to finish the front-end of my shopify wishlist app.
-My app uses a database with each record contains a product ID that the client has wishlisted.
The logic:
-I have a front-end shopify page with a div tag containing the client's ID. (if signed in)
-I use javascript to grab the client's ID and then grab all the product IDs from my app's database.
[Up to this point it works fine, I have the product IDs]
-Now I'm calling axios.post(appDomain + '/api/showWishlist', {shop_id: Shopify.shop,customer_id: customer})
-Inside my api.php file I have: Route::post('showWishlist', 'App\Http\Controllers\WishlistController#show');
-Which then my show function in my wishlistController file has php code that needs to return the product info (name, price, image, etc.) from the store's products.json.
This is where my problem lies. I can't seem to be able to grab the product info based on the ID. My original idea was to use graphQL in my controller function, but I believe that it only works for the website's owner as Auth::user() is required to run the graphQL?
How can I get the shopify product details (name,price,etc.) by using the product's ID from my wishlistController.php file?
Since you are already running an App, your best bet is re-factor it to be embedded (or just installed) in the shop itself, with permission to read products. In the front end, you use the App Proxy to call your App with product ID and customer IDs. You can then call Shopify, get the correct product information based on the IDs, and provide a nice JSON payload back to the front-end, all securely. This is the preferred pattern and without it, you're in for a tough slog. You could try tap-dancing with StorefrontAPI permissions, but still. You also expose your own App to abuse since you make no mention of you are securing your data. With the Shopify embedded App approach, you are protected.

Updating List of Entity Entries of DialogFlow Agent via API

Have been looking for a way to programmatically update our agent's entity entries for a certain entity type through the DialogFlow API. The purpose is to automate the updating of our entity entries on a scheduled basis (as our entries will be changing daily).
Came across this documentation page by Google on batch updating entity entries but have not been able to get anything better than a 404 when testing.
Have tried sending POST's via Postman using the supplied path and inserting my project name in URL but I believe I may be making naive mistakes as I am new to this area (specifically REST-stuff)
Below is an example of the current 404 response & path used.
We are just looking to get past the 404 error, once we have the contact setup, should be able to figure out auth & the rest.
There are several things you need to take into account.
The URL should look like this:
https://dialogflow.googleapis.com/v2/projects/julia-development-2/agent/entityTypes/actual_id/entities:batchUpdate
the "parent" you used in the URL is just the name of the path param
make sure "julia-development-2" is the id of your GCP project and not just the name
(Hint: when you click the drop-down for selecting a certain GCP project in the google cloud console, both the name and the ID of the project will be visibile in the list)
replace "actual_id" with the entity type id
Related to auth:
you need a bearer token in the Authorization header
to get this token you first need to download a JSON key from your projects service account and set the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to your JSON file. More details about setting up the service account and downloading the JSON key, you can find here: https://cloud.google.com/dialogflow/docs/setup
to get the token from the command line you can use
gcloud auth application-default print-access-token

Could not load the default credentials? (Node.js Google Compute Engine tutorial)

SITUATION:
I follow this tutorial: https://cloud.google.com/nodejs/tutorials/bookshelf-on-compute-engine
Everything works fine until I do npm start and go to:
http://localhost:8080
I am met with the following text on the blank page:
Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.
Which makes no sense since I am using OAuth. I followed the link and read the page, but I have no GOOGLE-APPLICATION-CREDENTIALS field anywhere, and nothing about it in the tutorial.
QUESTION:
Could you please reproduce the steps and tell me if you get the same result ?
(takes 5 minutes)
If not, what could I have done wrong ?
Yes, I had the same error. It's annoying cause Google Cloud Platform docs for their "getting started" bookshelf tutorial does not mention this anywhere. Which means that any new developer who tries this tutorial will see this error.
Read this:
https://developers.google.com/identity/protocols/application-default-credentials
I fixed this issue by running:
gcloud auth application-default login
In order to run thisgcloud auth application-default login
Visit: https://cloud.google.com/sdk/install
1) You have to install sdk into your computer
2) That will enable you to run the code
3) Log in to your associated gmail account then you are good to go!
This will make you login, and after that you code locally will use that authentication.
There are 2 solutions for this problem. One option, as mentioned by others, is to use gcloud auth application-default login
Second option is to set the environment variable GOOGLE_APPLICATION_CREDENTIALS. It should point to a file that defines the credentials. To get this file you need to follow these steps:
Go to the API Console Credentials page.
From the project drop-down, select your project.
On the Credentials page, select the Create credentials drop-down, then
select Service account key.
From the Service account drop-down, select an existing service account
or create a new one.
For Key type, select the JSON key option, then select Create. The file
automatically downloads to your computer.
Put the *.json file you just downloaded in a directory of your
choosing.
This directory must be private (you can't let anyone get access to
this), but accessible to your web server code.
Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the
path of the JSON file downloaded.
See https://developers.google.com/identity/protocols/application-default-credentials for details
Create a service account key using and download the json file. https://console.cloud.google.com/apis/credentials/serviceaccountkey
Add this to your ENV file
GOOGLE_APPLICATION_CREDENTIALS = "<PATH_TO_SERVICE_ACCOUNT_JSON_FILE>"
E.g:
GOOGLE_APPLICATION_CREDENTIALS=/Users/hello/Documents/ssh/my-10ebbbc8b3df.json
I was facing the same issue. It got fixed with following command.
gcloud auth application-default login
It stores default gcloud cloud credentials on your system and uses the same.
I got this error because of initially I did like below:
var admin = require("firebase-admin");
admin.initializeApp(); // I didnt add anything because firebaserc file include appName
It worked when I deployed the functions but not in serve. So this is how I solved it:
Go to the firebase Project settings(click on setting icon from side nav).
Click on the Service accounts.
Copy the admin sdk configuration snippet from selecting your pro. lang.
Ex (node.js):
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://your-domain.firebaseio.com"
});
Now we need to add serviceAccountKey.json file.
Click on the Manage service account permissions in top right corner.
Now, you will see services accounts for your project, in the table find the row with column name name and value firebase-adminsdk, in that row click on Action dots and select Create key.
From the pop up dialog select Key type as json and press create button.
You will prompt to download the file, download it to your functions directory in project(You can customize this as you want and if you pushing to github, make sure to ignore that file).
Now, if you save it into the same directory where you are initializeApp(), access that file like: ./socialape-15456-68dfdc857c55.json(In my case, both files are located: functions/index.js and functions/services.son in functions directory and in index.js file, I initialed my firebase admin sdk).
Ex(node.js):
const functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require("./myapp-15456-68dfdc857c55.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://myapp-15456.firebaseio.com"
});
It's a best and good idea to create .env file and include your file there and access it as others mentioned. I leave that part to you.
Hope this help someone on the planet. Regards!
If you're running the app locally, then the gcloud beta auth application-default login command should suffice for acquiring local credentials (I updated the tutorial to say so).
When running the app on Google Compute Engine, if the Compute Engine instance was created with the proper scopes (cloud-platform should be sufficient) then the app will authenticate with Google Cloud Platform APIs automatically without any extra work on your part.
Go here: https://firebase.google.com/docs/admin/setup#initialize_the_sdk and follow the instructions to create a private key.
Then after you have downloaded your private key open command prompt in the project directory and do the following command:
set GOOGLE_APPLICATION_CREDENTIALS=C:\YOUR-PATH\YOUR-KEY.json
use this to solve your issue. this actually works:-
just put credential parameter and give reference to your key to it.
const serviceAccount = require('../key.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
Another solution i found: in your package.json add an export command like this:
"scripts": {
"start": "export GOOGLE_APPLICATION_CREDENTIALS='./gcloud.json' && node ./bin/www --exec babel-node --presets babel-preset-env",
},
You have to create an object of your SessionsClient.
Here I will provide some steps, so you can run your code like a charm.
You have to go into your Dialogflow dashboard.
Click on setting ( Left navbar top-right gear icon)
in the General tab click Service Account link ( it will redirect you to another screen)
If you have a service account then ignore step 5
Create a service account ( Top-center +icon button)
Now you have a service account on a list click on
From the action, field presses the 3 vertical dots and create a key.
Download the JSON file on your local computer.
Assign object to your sessionClient.
const sessionClient = new dialogflow.SessionsClient({
keyFilename: "/var/www/html/moqatrips/dialog-flow.json"
});
For all people using firebase, what it worked for me was passing the credentials to the KeyManagementServiceClient constructor
const serviceAccount = require('../keys/file.json'); //<- your firebase credentials
const client = new KeyManagementServiceClient({
credentials: serviceAccount,
});
I also had this error problem, here I had not created the object of
keyFilename (stores the credentials of the api)
in the sessionClient object for nodejs app.
const sessionClient = new dialogflow.SessionsClient({
keyFilename: "./keyCredentials.json"
});
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
To download 'keyCredentials.json' goto:
https://console.cloud.google.com/apis/credentials/serviceaccountkey
Also add the path of this file to the system variables
In windows open powershell
type GOOGLE_APPLICATION_CREDENTIALS = [PATH_TO_SERVICE_ACCOUNT_JSON_FILE]
you may find youself in another part of the world -- and land here. I'm adding to a three year old question because its keywords matched my issue and the preceding answers helped me although none describe my issue
firebase deploy --only functions --debug
produced
[2020-12-02T08:31:50.397Z] FirebaseError: HTTP Error: 429, Unknown Error
Error: Could not read source directory. Remove links and shortcuts and try again.
I could not find anything wrong with the source directory. But that was all so many tiny fish.
Examining the error in detail, from the top, lead to:
Our systems have detected unusual traffic from your computer network. This page checks to see if it's really you sending the requests, and not a robot.
The block will expire shortly after those requests stop.
Out of curiosity and exhaustion, I waited first. The wait reset duration is > than 30 minutes. So i pursued the captcha to prove my enduring humanity which did register eventually after some oauth warnings.
Although this question has been answered multiple times, I found myself in a situation not explained here.
After I created the variable: $GOOGLE_APPLICATION_CREDENTIALS, I was getting the same error as Coder1000.
However, I was running both: nodemon and: npm run dev in two separate sessions in Terminal, neither of which were aware of the variable.
Once I: shut the tabs down; added new tabs; and ran the commands again, the application was able to access the variable.
download Cloud SDK installer from this site. https://cloud.google.com/sdk/docs/install
run this command -> gcloud auth application-default login
If anyone ran into the issue just like me and doesn't want to set the variable each time before running their code it's best to manually set the environment variable. Name it GOOGLE_APPLICATION_CREDENTIALS and browse the downloaded JSON file. If you don't know the steps follow this: https://docs.oracle.com/en/database/oracle/machine-learning/oml4r/1.5.1/oread/creating-and-modifying-environment-variables-on-windows.html#GUID-DD6F9982-60D5-48F6-8270-A27EC53807D0

Using local MySQL database with PHP & JavaScript on Google Maps

I am attempting to follow this tutorial - https://developers.google.com/maps/articles/phpsqlajax_v3
I have a rather fundamental & simplistic question.
Using firefox, I can see this error when I load the html page with the php and javascript built in, as taken from the tutorial above.
TypeError: xml is null
The MySQL database I have is on my computer and is not hosted on the website in question. So, when I run the php script that exports the xml in the command line, I can see that it functions correctly.
I attempted to add my ip address to the phpsqlajax_dbinfo.php file, such that -
<?php
$username="";
$password="";
$database="";
$host="";
?>
But this results in a connection error.
What changes do I need to make for this to be able to reference the database on my computer, rather than one on the site?
EDIT
I have verified that the host, database, password and username fields are correct. I am able to run the phpsqlajax_genxml.php file from the command line.
If you run MySql on your computer use "localhost" as a server in phpsqlajax_dbinfo.php:
$server="localhost";
Your MySql DB is probably not set up to listen to your public IP, if you really want to use your IP you can add it to my.cnf, but I would really recommend using localhost:
bind-address = your_ip

How to set up a Google Drive Client ID for access without a local server?

I'm wondering if it's possible to, say, open up a jsfiddle on a random computer and log in and authenticate and use the drive API, without having to have a local server running all the time? And how exactly does one go about setting this up? I'm sorry if this is a simple question but I'm just sorta lost because the instructions that I've found so far are unclear.
Edit:
So far I have, following from here and here:
Created a project via the Google Developers Console.
Opened up that project there, navigated to APIs under APIs & auth, and ensured that Drive API was enabled
Went into credentials, and clicked on "Create a new Client ID"
Selected "Web Application"
Set authorized javascript origins to http://localhost:4567
Deleted any contents in Redirect URI's and left it blank, then pressed "Create Client ID."
Took a sample like this, this, or this, and stored it in a local file named named index.html.
This wouldn't run by simply opening in a brower, so I had to host a local server
I navigated into that directory in the command line and then typed "python -m SimpleHTTPServer 4567" (without the quotes) and this hosted a local server
Opened http://localhost:4567 in my web brower, and all of these samples work fine, after copying the newly created client ID into these files where they ask for it.
I also have made a python application, to use pydrive I:
Clicked on "Create a new Client ID", then "Installed Application" and "Other", then "Create Client ID."
Next I went to the Old Google APIs Console, clicked on API Access, found that client ID, and clicked Download JSON.
I placed this client_secrets.json next to my python application, and this allowed pydrive to authenticate successfully and I could access and modify my google drive files anywhere using that client ID. Though of course I deleted this client_secrets.json before giving the application to another person, and showed them how to do this process as well.
However, beyond this, I'm a little unsure about, specifically:
How one can use the drive api in web applications without having to set up a local server, say simply by running code in jsfiddle and having requests sent through my project via using a Client ID, and
If a local server is set up that can be accessed by anyone on the web, how one can modify the above steps to allow any client to open that server's webpage to use the google drive API?
I know that I most likely need to set up a Public API access in the developers console, but am not entirely sure what Referers I should use as well. So is there a simple way to do any of this?
I also know that gspread can open google excell spreadsheets only using the client's username and password, so I'm suspecting that what I'm looking for is possible, but I'm not sure.
Okay, so I found a solution that works pretty well:
Make an OAuth.io account (It's free).
Once you're logged in, go to your oauth.io dashboard.
You should be looking at a Default App, or you can make another one it doesn't really matter.
Under "Domains & URLs whitelist", you'll see a little box that says "localhost." Type in "
http://fiddle.jshell.net/" (without the quotes) and press enter. This allows any jsfiddle to authenticate with your application
Next, we need to enable Google Drive support
Go to the Google Developers Console
Like before, navigate to Credentials under APIs and Auth.
Click "Create new Client ID"
Select Web Application
Under "Redirect URIs" put "https://oauth.io/auth" and "http://oauth.io/auth" (without quotes, on separate lines)
Under "Javascript Origins" put "https://oauth.io" and "http://oauth.io"
Press "Create Client ID"
Now go to your Oauth.io key manager. Click on Google Drive in the list to the left. Press next, and enter your client_id and client_secret that you created in the previous step (via the Google Developers Console)
Select online (at least online is preferred since offline should be for server side only)
Click on the Scope text book, and select "https://www.googleapis.com/auth/drive (View and manage the files in your google Drive)."
Press finish. Now click on the Try Auth button, and hopefully you should get some output like
{
"access_token": "ya29.AwH-1N_gnstLBuZfOR4W9CCcggKrQpMyKYV4QVEtCiIzHozNU5AfUJoYQzukALfjdiw2iOCUve7JbQ",
"token_type": "Bearer",
"expires_in": 3600,
"provider": "google_drive"
}
To use this, you can do something like:
// This only works because we're set to "No wrap - in <head>"
function ShowDriveFileList() {
var accessToken;
// Initialize OAuth with our key
OAuth.initialize('lmGlb8BaftfF4Y5en_c8XYOSq2A');
// Connect to google drive, and print out file list
OAuth.popup('google_drive').done(function (result) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "https://www.googleapis.com/drive/v2/files", false);
xmlHttp.setRequestHeader("Authorization", "Bearer " + result.access_token);
xmlHttp.send(null);
alert(xmlHttp.responseText);
}).fail(function (err) {
alert(err);
});;
}
Which you can find at http://jsfiddle.net/JMTVz/41/. This uses my oauth.io client id, but you can replace it with yours and it should work as well.
You can do the same thing using the OAuth Playground.
See How do I authorise an app (web or installed) without user intervention? (canonical ?)
Step 11 will be different. Instead of pasting the refresh token into your server app (which you don't have), you'll paste the access token into your JS in the same way as you are doing in your answer.

Categories