Showing posts with label Google Play game services. Show all posts
Showing posts with label Google Play game services. Show all posts

Saturday, February 20, 2016

Using Credentials between your Server and Google Services

Posted by Laurence Moroney, Developer Advocate



This is part 4 of a series on Google Sign-In that began with a blog post on the user experience improvements that launched with Google Play services 8.3. We then discussed the API updates that make the programming model much easier. Most recently, we went into how you can use Google Sign-In to authenticate a user with your backend server.



In this post, we’ll discuss how you can have your users sign in via your app to authorize your service for access to Google APIs, such as Google Drive, on their behalf.



When using Google Sign-In, it is easy to extend your integration with Google by requesting additional scopes for API access after sign-in, like storing the user’s pictures of food in Google Drive. Typically, you should request this access incrementally (not at initial sign-in) -- i.e. in the context of a user’s actions (for example, after an app user’s order has been delivered and they’d like to save a copy of their food photos), following best practices in user experience to make it most likely that the user will grant access, and aligning with the runtime permissions model in Android Marshmallow 6.0.



When you do this kind of integration, you probably want to access data from your server, so that you can continue to have access when the user is offline, or to store user-generated data in your own database. This flow would look like Figure 1. This also has the advantage of working across all platforms.





Figure 1. Accessing Google Services with Credentials.



To do this, follow these steps:



Step 1: As with the scenario in server authentication covered in the previous post, this sample provides canonical code for your Android app. In particular see the ServerAuthCodeActivity.




 GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
.requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
// The serverClientId is an OAuth 2.0 web client ID
// Details at: https://developers.google.com/identity/sign-in/android/?utm_campaign=android_discussion_server_021116&utm_source=anddev&utm_medium=blogstart step 4
.requestServerAuthCode(serverClientId)

.requestEmail()
.build();


This requires you to get a web client ID for your server. Details on how to obtain this are available here (see Step 4).



In this case, the scope DRIVE_APPFOLDER is requested, meaning that the user will be asked to give the app permission to access their Google Drive. In addition to this, a server auth code will be requested.



If the sign-in is successful, the auth code can be extracted from the account object like this:




 if (result.isSuccess()) {  
GoogleSignInAccount acct = result.getSignInAccount();
String authCode = acct.getServerAuthCode();
}


(Taken from onActivityResult in the sample here)



This auth code should then be sent to your server using HTTPS POST, and, after it is exchanged, will give your server access to the user’s Google Drive. [Important: you should send the code in an authenticated call to your backend to ensure that it is a legitimate request from the active user].



Step 2: On your server, you will then exchange the auth code for tokens using the GoogleAuthorizationCodeTokenRequest class:




 // Set path to the Web application client_secret_*.json file you downloaded from the  
// Google Developers Console: https://console.developers.google.com/project/_/apiui/credential
// You can also find your Web application client ID and client secret from the
// console and specify them directly when you create the GoogleAuthorizationCodeTokenRequest
// object.
String CLIENT_SECRET_FILE = "/path/to/client_secret.json"; // Be careful not to share this!
String REDIRECT_URI = "/path/to/web_app_redirect" // Can be empty if you don’t use web redirects
// Exchange auth code for access token
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(
JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
"https://www.googleapis.com/oauth2/v4/token",
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
authCode,
REDIRECT_URI)
.execute();
String accessToken = tokenResponse.getAccessToken();
String refreshToken = tokenResponse.getRefreshToken();
Long expiresInSeconds = tokenResponse.getExpiresInSeconds();
// You can also get an ID token from the exchange result if basic profile scopes are requested
// e.g. starting GoogleSignInOptions.Builder from GoogleSignInOptions.DEFAULT_SIGN_IN like the
// sample code as used here: http://goo.gl/0Unpq8
//
// GoogleIdToken googleIdToken = tokenResponse.parseIdToken();


Then, create a GoogleCredential object using the tokens from GoogleTokenResponse:




 GoogleCredential credential = new GoogleCredential.Builder()  
.setTransport(new NetHttpTransport())
.setJsonFactory(JacksonFactory.getDefaultInstance())
.setClientSecrets(clientSecrets)
.build();
credential.setAccessToken(accessToken);
credential.setExpiresInSeconds(expiresInSeconds);
credential.setRefreshToken(refreshToken);


If a refresh token is available, you can persist the credentials using StoredCredential for later use if you need ongoing access to the API on behalf of the user.



Step 3: The credential can then be used to access Google services. Now, in our food delivery scenario, you might want to store or retrieve photos or receipts of finished deliveries in Google Drive. For example, it would look something like this:




 Drive drive = new Drive.Builder(new NetHttpTransport(),   
JacksonFactory.getDefaultInstance(),
credential)
.setApplicationName("Auth Code Exchange Demo")
.build();
File file = drive.files().get("appfolder").execute();


This demonstrates the use of Google Sign-In credentials where your server can make Google API calls on behalf of your users. To learn more about this, and all Google Sign In technologies, visit the Google Identity Platform website.



Tuesday, January 26, 2016

New features to better understand player behavior with Player Analytics

Posted by Lily Sheringham, Developer Marketing at Google Play



Google Play games services includes Player Analytics, a free reporting tool available in the Google Play Developer Console, to help you understand how players are progressing, spending, and churning. Now, you can see what Player Analytics looks like with an exemplary implementation of Play games services: try out the new sample game in the Google Play Developer Console, which we produced with help from Auxbrain, developer of Zombie Highway 2. The sample game uses randomized and anonymized data from a real game and will also let you try the new features we’re announcing today. Note: You need a Google Play Developer account in order to access the sample game.



Use predictive analytics to engage players before they might churn



To help you better understand your players’ behavior, we’ve extended the Player Stats API in Player Analytics with predictive functionality. The churn prediction method will return data on the probability that the player will churn, i.e., stop playing the game, so you can create content in response to this to entice them to stay in your game. Additionally, the spend prediction method will return the probability that the player will spend, and you could, for example, provide discounted in-app purchases or show ads based on these insights.



Create charts in the new funnels report to quickly visualize sequences of events



The funnels report enables you to create a funnel chart from any sequence events, such as achievements, spend, and custom events. For example, you could log custom events for each step in a tutorial flow (e.g., tutorial step 1, step 2, step 3), and then use the funnel report to visualize the exit points in your tutorial.






Measure and compare the effect of changes and cumulative values by new users with cohort’s report



The cohorts report allows you to take any event such as sessions, cumulative spend, and custom events, and compare the cumulative event values by new user cohorts - providing valuable insight into the impact of your decisions on your gaming model. For example, you can view users that started the day before you made a change and the day after. This allows you to measure and compare the effect of changes made, so if you doubled the price of all your items in your in-game store, you can see if the cumulative sessions started after the change was lower or higher than the users that started before the change.





Updated C++, iOS SDKs and Unity plug-in to support Player Stats API




We have updated the C++ and iOS SDKs, and the Unity plug-in, all of which now support the Player Stats API, which includes the basic player stats as well as spend and churn predictions.

Be sure to check out the sample game and learn more about Play Games Services. You can also get top tips from game developer Auxbrain to help you find success with Google Play game services.



Sunday, January 24, 2016

Play Games Permissions are changing in 2016

Play Games Permissions are changing in 2016

Posted by Wolff Dobson, Developer Advocate



We’re taking steps to reduce sign-in friction and unnecessary permission requests for players by moving the Games APIs to a new model. The new interaction is:




  • Players are prompted to sign-in once per account, rather than once per game

  • Players no longer need their account upgraded to Google+ to use Play Games services

  • Once players have signed-in for the first time, they will no longer need to sign in to any future games; they will be automatically signed in

  • Note: Players can turn off auto-sign-in through the Play Games App’s settings



Advantages:


  • Once a user signs in for first time, new games will generally be able to sign in without any user interaction

  • There is no consent screen required for signing in on any particular game. Sign-in will be automatic to each new game.



In order to respect user’s privacy and avoid revealing their real name, we also have to change the way player IDs work.




  • For existing players: Games will continue to get their Google+ ID (also called “player ID” in previous documentation) when they sign in.

  • For new players: Games will get a new player ID which is not the same as the previous IDs we’ve used.



Potential issues



Most games should see no interruption or change in service. There are a handful of cases, however, where some change is required.



Below are some issues, along with potential solutions.



These are:



  1. Asking for the Google+ scope unnecessarily

    • Issue: Your users will get unnecessary, potentially disturbing pop-up consent windows
    • Solution: Don’t request any additional scopes unless you absolutely need them

  2. Using the Play Games player ID for other Google APIs that are not games

    • Issue: You will not get valid data back from these other endpoints.
    • Solution: Don’t use player ID for other Google APIs.

  3. Using mobile/client access tokens on the server

    • Issue: Your access token may not contain the information you’re looking for

      • ...and this is not recommended in the first place.

    • Solution: Use the new GetServerAuthCode API instead.



Let’s cover each of these issues in detail.



Issue: Asking for unnecessary scopes


Early versions of our samples and documentation created a GoogleApiClient as follows:



 // Don’t do it this way!  
GoogleApiClient gac = new GoogleApiClient.Builder(this, this, this)
.addApi(Games.API)
.addScope(Plus.SCOPE_PLUS_LOGIN) // The bad part
.build();
// Don’t do it this way!


In this case, the developer is specifically requesting the plus.login scope. If you ask for plus.login, your users will get a consent dialog.



Solution: Ask only for the scopes you need


Remove any unneeded scopes from your GoogleApiClient construction along with any APIs you no longer use.


 // This way you won’t get a consent screen  
GoogleApiClient gac = new GoogleApiClient.Builder(this, this, this)
.addApi(Games.API)
.build();
// This way you won’t get a consent screen


For Google+ users


If your app uses specific Google+ features, such as requiring access to the player’s real-world Google+ social graph, be aware that new users will still be required to have a G+ profile to use your game. (Existing users who have already signed in won’t be asked to re-consent).



To require Google+ accounts to use your game, change your Games.API declaration to the following:


 .addApi(Games.API, new GamesOptions.Builder()  
.setRequireGooglePlus(true).build())


This will ensure that your game continues to ask for the necessary permissions/scopes to continue using the player’s real-world social graph and real name profile.



Issue: Using the Player ID as another ID


If you call the Games.getCurrentPlayerId() API, the value returned here is the identifier that Games uses for this player.



Traditionally, this value could be passed into other APIs such as Plus.PeopleApi.load. In the new model, this is no longer the case. Player IDs are ONLY valid for use with Games APIs.



Solution - Don’t mix IDs


The Games APIs (those accessed from com.google.android.gms.games) all use the Player ID, and as long as you use only those, they are guaranteed to work with the new IDs.



Issue: Using mobile/client access tokens on the server


A common pattern we’ve seen is:



  • Use GoogleAuthUtil to obtain an access token

  • Send this token to a server

  • On the server, call Google to verify the authenticity. This is most commonly done by calling https://www.googleapis.com/oauth2/v1/tokeninfo and looking at the response



This is not recommended in the first place, and is even more not-recommended after the shift in scopes.



Reasons not to do this:



  • It requires your app to know the current account the user is using, which requires holding the GET_ACCOUNTS permission. On Android M, this will result in the user being asked to share their contacts with your app at runtime, which can be intimidating.

  • The tokeninfo endpoint isn’t really designed for this use case - it’s primarily designed as a debugging tool, not as a production API. This means that you may be rate limited in the future if you call this API.

  • The user_id returned by token info may no longer be present with the new model. And even if it is present, the value won’t be the same as the new player ID. (See problem 2 above)

  • The token could expire at any time (access token expiration times are not a guarantee).

  • Using client tokens on the server require extra validation checks to make sure the token is not granted to a different application.



Solution: Use the new GetServerAuthCode flow



Fortunately, the solution is known, and is basically the same as our server-side auth recommendations for web.





  1. Upgrade to the latest version of Google Play Services SDK - at least 8.4.87.

  2. Create a server client ID if you don’t already have one

    1. Go to the Google Developer Console, and select your project

    2. From the left nav, select API Manager, then select Credentials

    3. Select “New Credentials” and choose “OAuth Client ID”

    4. Select “Web Application” and name it something useful for your application

    5. The client id for this web application is now your server client id.

  3. In your game, connect your GoogleApiClient as normal.

  4. Once connected, call the following API:

    1. Games.getGamesServerAuthCode(googleApiClient, “your_server_client_id”)

    2. If you were using GoogleAuthUtil before, you were probably calling this on a background thread - in which case the code looks like this:




 // Good way  
{
GetServerAuthCodeResult result =
Games.getGamesServerAuthCode(gac, clientId).await();
if (result.isSuccess()) {
String authCode = result.getCode();
// Send code to server.
}
}
// Good way



  1. Send the auth code to your server, exactly the same as before.

  2. On your server, make an RPC to https://www.googleapis.com/oauth2/v4/token to exchange the auth code for an access token, probably using a Google Apis Client Library.

    1. You’ll have to provide the server client ID, server client secret (listed in the Developer Console when you created the server client ID), and the auth code.

    2. See more details here: https://developers.google.com/identity/protocols/OAuth2WebServer?utm_campaign=play games_discussion_permissions_012316&utm_source=anddev&utm_medium=blog#handlingresponse

    3. No, really:  You should use a Google Apis Client Library to make this process easier.

  3. Once you have the access token, you can now call www.googleapis.com/games/v1/applications/<app_id>/verify/ using that access token.

    1. Pass the auth token in a header as follows:

      1. “Authorization: OAuth <access_token>”

    2. The response value will contain the player ID for the user. This is the correct player ID to use for this user.

    3. This access token can be used to make additional server-to-server calls as needed.

Note: This API will only return a 200 if the access token was actually issued to your web app.




In summary


Let’s be very clear: If you do nothing, unless you are depending explicitly on Google+ features, you will see no change in functionality, and a smoother sign-in experience.



If you are:




  • Requesting Google+ scopes without using them, it’s a good idea to stop using them from here out.

  • Sending client access tokens to your server, we strongly suggest you use getGamesServerAuthCode() instead.



Thanks, and keep making awesome games!













Thursday, November 12, 2015

Developer tips for success with Player Analytics and Google Play games services

Posted by, Lily Sheringham, Developer Marketing at Google Play



Editor’s note: As part of our series featuring tips from developers, we spoke to some popular game developers to find out how they use Player Analytics and Google Play game services to find success on Google Play. - Ed.



Google Play games services, available in the Developer Console, allows you to add features such as achievements and leaderboards to your games. Google Play games services provides Player Analytics, a free games-specific analytics tool, in the Developer Console Game services tab. You can use the reports to understand how players are progressing, spending, and churning backed by a data-driven approach.





Bombsquad grows revenue by 140% per user with Player Analytics



Independent developer Eric Froemling, initially created the game Bombsquad as a hobby, but now relies on it as his livelihood. Last year, he switched the business model of the game from paid to free-to-play. By using Player Analytics, he was able to improve player retention and monetization in the game, achieving a 140% increase in the average revenue per daily active user (ARPDAU).



Watch the video below to learn how Eric uses Player Analytics and the Developer Console to improve gamers’ experience, while increasing retention and monetization.













Tips from Auxbrain for success with Google Play games services



Kevin Pazirandeh, founder and CEO of games developer Auxbrain, creator of Zombie Highway, provides insight into how they use Google Play games services, and comments:



“While there are a few exceptions, I have not run into a better measure of engagement, and perhaps more importantly, a measure for change in engagement, than the retention table. For the uninitiated, a daily retention table gives you the % of players who return on the nth day after their first play. Comparing retention rates of two similar games can give you an immediate signal if you are doing something right or wrong.”



Kevin shares his top tips on how to best use the analytics tools in Google Play games services:



  1. You get Player Analytics for free - If you’ve implemented Google Play game services in your games, check out Player Analytics under Game services in the Developer Console, you’ll find you are getting analytics data already.


  2. Never assume change is for the better - Players may not view changes in your game as the improvement you had hoped they were. So when you make a change, have a strategy for measuring the result. Where you cannot find a way to measure the change’s impact with Player Analytics, consider not making it and prioritize those changes you can measure.


  3. Use achievements and events to track player progress - If you add achievements or events you can use the Player progression report or Event viewer to track player progress. You’ll quickly find out where players are struggling or churning, and can look for ways to help move players on.


  4. Use sign-in to get more data - The more data about player behavior you collect, the more meaningful the reports in Player Analytics become. The best way to increase the data collected is to get more players signed-in. Auto sign-in players, and provide a Play game services start point on the first screen (after any tutorial flow) for those that don’t sign-in first time.


  5. Track your player engagement with Retention tables - The Retention table report lets you see where players are turning away, over time. Compare retention before and after changes to understand their impact, or between similar games to see if different designs decisions are turning players away earlier or later.


Get started with Google Play Games Services or learn more about products and best practices that will help you grow your business on Google Play globally.

Saturday, October 24, 2015

Virtual currency: Sources and Sinks

Posted by Damien Mabin, Developer Advocate



More and more mobile games base their economic model on virtual currencies and free to play, yet there are plenty of pitfalls to be aware of while developing your game. One of these pitfalls is having an unbalanced economy. Sources and Sinks, a handy feature included in the Play Games Services toolset, is specifically designed to help measure the balance of your game’s virtual economy.



It helps you visualise in one simple diagram the state of your current in game economy. In diagram 1 (below), along the x-axis (time), and y-axis (amount of virtual currency), we see 2 curves:




  • One showing the amount of virtual currency earn by players (orange line)

  • The other one showing the amount spent by players (green line)





Diagram 1: Poorly Monetizing Economy



What do the curves in the diagram tell us? In this case, that our game is likely not going to monetize well. Users are spending less currency than they are earning: resulting in a surplus. There is no sense of scarcity for the user which may indicate that your players do not understand how they can spend currency or that there is value to them in doing so. It would be a good idea in this case to re-evaluate how much content is available to spend virtual currency on and how discoverable this content is to your users. Alternatively, you may want to consider decreasing the amount of in game earned currency is available (inflation can be a bad thing). Ultimately, you want your curves to change as demonstrated in diagram 2 (below).




Diagram 2: Balancing economy



That’s a lot better! Now your users are spending more than they earn… Wait! How is that possible? Two reasons: Players are spending the stock of money they accumulated before your changes. Moreover, there is another important point not to forget: you should not track in the above diagrams the amount of virtual currency the user purchase through in app purchases. If you wait a few more days, you should see the 2 curves converge a bit; the delta of them being the amount of virtual currency users purchase through IAP:




Diagram 3: Stabilised economy



With play game services you can get this visualisation with 2 lines of codes! It works on iOS and Android and doesn’t require the user to sign in to Play Games. What you will have in your Android or iOS app is something like this:





You can find more information about the integration here.



Once the client integration done you can go into your Play Store Developer Console to visualise the curve. Go into the “Game services” section, and click on “Player analytics->overview.”