Author Topic: Guide: PlayFab integration  (Read 3926 times)

Offline Baroni

  • Administrator
  • *****
  • Posts: 1364
    • View Profile
Guide: PlayFab integration
« on: July 07, 2017, 08:57:22 pm »
PlayFab integration is in active development. Please see chapter 1 below for current limitations and restrictions that apply.

This guide explains how to configure PlayFab services for Simple IAP System, specifically cloud save and receipt validation. Additionally, methods are being explained for keeping local user inventory in sync with PlayFab.

Table of Contents:
  • Prerequisites
  • Creating a PlayFab account
  • Creating your store catalog
  • Importing the PlayFab Unity SDK
  • Using receipt validation only
  • Logging in the user in Unity
  • Feature Overview
  • In-game Synchronization
  • Adding Cloud Scripts



1.   Prerequisites

What else can you do to avoid cheating? To put it simple Ė donít do everything on the client, but verify each user action on external servers. The PlayFab 'full' integration in Simple IAP System (not only receipt verification) is a great starting point for that by keeping everything in sync with cloud save and doing critical transactions (like purchasing) on their servers only.

To not postpone big updates several months, we've decided to implement PlayFab in 3 phases in Simple IAP System:
  • 1. phase: cloud save requires an online connection at all times. No data is saved on the device.
  • 2. phase: save data on the device too. Handle data conflicts caused by different server or local data version in a popup presented to the user.
  • 3. phase: hybrid - make it possible to go from online > offline or offline > online during the game. Compare local/server data and handle data conflicts automatically based on developer defined merging rules.
The first phase is what landed in the initial 4.0 version of Simple IAP System. As it requires an online connection throughout the whole play session, it is the most secure solution by far, altough better suited at devices supporting a reliable internet connection (desktop pc's via ethernet or mobile devices using wi-fi). Please keep that in mind when making use of this first iteration. Basically you have two options with online-only games when there is no internet connection available:
  • logging into PlayFab is not possible - it would be best to disallow entering the game at this state
  • or, only permit offline mode without earning & spending (such as a training mode with local scores)

Also note that with the various different native plugins supporting mobile login via PlayFab (i.e. Play Game Services by Google), each of them would need a separate integration guide in Unity. That's something that is already being worked on, but that's why they're not quite ready yet for the first release. Unless you're implementing this yourself, the default login method is via registered email addresses for now (except for Facebook, more on this in chapter 6), which is the most common technique for desktop applications.

With that out of the way, let's continue by creating your PlayFab developer account.



2.   Creating a PlayFab account   

Creating a PlayFab developer account is easy and free. Sign up here: https://developer.playfab.com

Once you're logged in, you will be greeted by a somewhat empty screen, where you can define your company and game name. In PlayFab, when speaking about games, they are usually referred to as 'titles'. Each game must have its own title (or dashboard), which is used to independently track users, purchases, cloud scripts and all the other stuff PlayFab provides.

If you've created your first title, it should be shown under your games page along with its generated title identifier.





3.   Creating your store catalog

Now with the title created in PlayFab, we need a way to transfer all the different in-app purchase products from Unity to PlayFab. Fortunately, this is very easy by using the JSON export provided in Simple IAP System, as it already contains the correct format and properties. Open the IAP Settings editor under Window > Simple IAP System > IAP Settings. Clicking on the 'Export to JSON' button and choosing an export folder will result in the following files being created:



  • SimpleIAPSystem_Currencies.json (currencies with name and default value)
  • SimpleIAPSystem_IAPSettings.json (all IAP products, including free ones)
  • SimpleIAPSystem_IAPSettings_PlayFab.json (all IAP products, excluding free ones)
You will make use of the files highlighted in bold. As it's unnecessary to save or auto-grant free products in PlayFab, they are not tracked on their servers at all, but only exist in your game.

In order to import your products in PlayFab, head over to your title's Economy > Currencies section. Click the 'Upload JSON' button and select the previously created SimpleIAPSystem_Currencies.json file. We have to import currencies first, since other products cannot be created when using a non-existent currency.



After that, go to the Economy > Catalogs section and upload all of your IAP products as well, by clicking on 'Upload JSON' and selecting the SimpleIAPSystem_IAPSettings_PlayFab.json file. You can then click on your catalog ID and verify that all products and currency bundles are actually there.





Make this catalog your primary catalog by clicking on the small settings icon and toggling the 'Primary Catalog' checkbox. You can see that everything is correct when the catalog is showing 'Primary' in its header.





4.   Importing the PlayFab Unity SDK

First of all, download the PlayFab Unity SDK from here: https://api.playfab.com/sdks/unity

You have several download options on this page, but I would recommend downloading the regular 'PlayFab SDK'. The 'Editor Extensions' helper is a nice idea, which didn't work out the last time I've tried it, as it lost connection to PlayFab's server and the title quite often. So if you don't want to update the SDK every week, just go with the regular download.



After downloading, import the PlayFab SDK into your Unity project. For establishing the relation between the SDK and your title on PlayFab's servers, you will have to enter its title ID in the SDK settings. Locate the 'PlayFabSharedSettings' file in your project as shown below, then enter the title ID that has been generated for you in PlayFab's dashboard (see first screenshot in this thread).

   

Lastly, since the IAPManager needs to be aware that you are now going to use PlayFab features as well, you have to drag and drop our PlayfabManager prefab found under SimpleIAPSystem > Prefabs > Resources in the same scene like the IAPManager. If you don't do this, a temporary instance of the PlayfabManager (along with a warning message) will get instantiated so your app will continue working.





5.   Using receipt validation only

'Receipt validation only' means that in-app purchase receipts from your app will get sent to PlayFab for validation and approval, but you are not planning to use any other PlayFab features (cloud save, cloud scripts, analytics, product sales, and so on). In this case, open up the Plugin Setup editor under Window > Simple IAP System > Plugin Setup and choose 'Validation Only'. If you would like to use the full PlayFab suite by selecting 'Full Suite', you have to do the following steps as well.

Please make sure that you have first read and understood the concepts in the Receipt Verification chapter in our documentation PDF (included in Simple IAP System), and followed the section about Service Receipt Verification described there, specifically adding the ReceiptValidatorService component to your IAPManager prefab. This is necessary regardless of the PlayFab mode 'Validation Only' or 'Full Suite'.



For verifying real in-app purchase receipts, PlayFab needs some of your App Store secret keys to validate their authenticity for you. Head over to the Add-ons section, where you'll be able to find the platforms supported for receipt validation: Amazon (under Monetization), Apple and Google (under Platforms).



Click on the platforms you would like to use and enter the credentials necessary for receipt validation. If you've successfully activated them, they should show a green label saying that.

If you've followed the guide until now and only want to use receipt validation, you've made it! No other steps are required for you at this point.
Please play-test your game with 'Development Build' enabled and check that purchases are actually getting verified correctly.

On the other hand, if you are using the 'Full Suite' mode in our Plugin Setup window, then there are still a few steps waiting for you - please follow along until the end.



6.   Logging in the user in Unity

With PlayFab being in 'Full Suite' mode, our DBManager will not save any data locally on the device. This refers to the DBManager's 'Memory Only' mode, which is activated automatically for this, and means that players need to "download" their own data from the PlayFab servers each time your app is launched. This complies with a high-security app environment, as there is no local data or any save games regarding in-app purchases that could be tampered with.

However, this also means that players need a way to get their purchase data, and only their data, back whenever they launch the app. That's why users have to log in to the PlayFab servers using their account credentials (requiring an active internet connection), so they can continue playing where they left off. In order to do this, Simple IAP System provides a very basic login scene named 'UserLogin'.



At this state, users need to register with their email + password for creating their own account. This account should then be used in subsequent app sessions by logging in with the same credentials. A password recovery method is also provided, in case the user actually entered a valid email address he has access to.

An exception to this login technique are platforms which already have a common authentication system, such as Facebook and Steam. By design, users on these platforms are already signed in before they open the app. This is why instead of using the approach described above there too (effectively doubling the registration process), the existing authentication system is used to auto-login the user - they do not need to enter anything and their PlayFab account is connected automatically, even when logging in from different devices.

Remember, since the login scene should now be the first scene of your app, it needs to contain the IAPManager and PlayfabManager prefabs for initialization purposes, but also be declared as the first scene in your Build Settings:





7.   Feature Overview

Now that we've implemented PlayFab user management, in this chapter we're going to take a look at what we can do with that integration.

Receipt Validation
Receipt validation happens whenever users purchase a product in the shop. When using the 'Validation Only' mode, only purchases for real money are being validated at the time they happen - however, the result is not really synced with PlayFab, but directly saved to the device. In 'Full Suite' mode, both real money and virtual purchases, as well as the result (e.g. inventory and virtual currency balances) are synchronized with PlayFab - nothing exists locally on the device.

Validating purchases with PlayFab allows you to go into great detail about monetization, track purchase amounts across platforms and even inspecting single users on what they bought in your game. For a more aggregated summary on what your users are buying in your game, along with how often they do it, you can set up a query in the Analytics section for a bar chart analysis.








Cloud Save (Full Suite mode)
Since all transaction related actions are acknowledged by the PlayFab servers, they are registered on the user's PlayFab account. In the user's perspective this means that, combined with a login system described in the last chapter, users can switch devices, uninstall & reinstall the app, still retrieve their data and continue playing without any loss of data (more on synchronization in the next chapter). In an administrator's perspective (yours), having everything flowing over PlayFab's servers allows you to control virtual currency economies, modifying currency balances or inventory of hacking users, banning their accounts, giving out product keys as promotions or just looking at what your players are doing.




Introducing Sales (Full Suite mode)
Temporary sales for products could be a way to make specific items or purchases in general more appealing - the big benefit here is that you can introduce IAP sales without updating your app. If you know you would like to run sales in the future, just check 'Fetch' for both real money and virtual products in the IAP Settings editor.



What this does is not only fetching and displaying prices of real money products from the App Stores, but also downloading current prices from your title's economy catalog in PlayFab. So in order to run a sale for a specific product, just open it in PlayFab's catalog and edit its price. The new price will be effective when users relaunch your app.





8.   In-game Synchronization

Many game actions are automatically synchronized with PlayFab at the time they happen in your app. This applies to everything that requires an interaction with PlayFab's servers, basically. For example, these are the actions which get auto-synced:
  • user purchases real money product (product is assigned to inventory)
  • user purchases virtual currency (currency amount is updated)
  • user purchases virtual product (currency amount is updated, product is assigned to inventory)
  • user purchases virtual product with usage count (currency amount is updated, usage is updated in Player Data (Title))
  • user selects/unselects product (selection value is updated in Player Data (Title))



As you can see, most of the shop synchronization is handled for you already. What Simple IAP System cannot know though, is what you are doing with these items in your game. This means that everything dependent on your own game-specific use case also has to be handled and synchronized by you. The PlayfabManager (link to Scripting Reference) provides several methods, described below, for syncing your data back to PlayFab. Each method is explained with a sample use case and the point when it's best to call it.

SetPurchase
Use case: the player finds a new weapon in-game and you would like to give it to him for free. Note that this method is best suited for non-consumable products, as for consumable products you should call the other methods directly to minimize web requests.
When: at any point during the game.

SetPlayerData
Use case: the player previously bought some power-ups with usage count. He then activates them in-game, which you are tracking via DBManager.IncreasePlayerData by passing in a negative value (to substract the power-up usage count). You then want to synchronize the remaining usage count with PlayFab by calling this method.
When: only at the end of a round or level, to minimize web requests.

SetFunds
Use case: the player collects coins during the game, which you are tracking via DBManager.IncreaseFunds. You then want to synchronize the current currency amount with PlayFab by calling this method.
When: only at the end of a round or level, to minimize web requests.

SetSelected
Use case: you have an in-game inventory display where players can select and deselect e.g. weapons. Note that the selection in the shop scene is synced for you already.
When: at any point during the game.



9.   Adding Cloud Scripts

Some of the methods listed in the previous chapters are calling custom code on PlayFab's servers, referred to as "cloud scripts". Each title on PlayFab has its own server code section, where you can execute actions which should not be in the hands of users (to prevent hacking), such as granting products or virtual currency, or just to add another security measure by checking the values it receives for feasibility. You have to add some server methods to your cloud script, so that Simple IAP System is able to properly call them for your title. On PlayFab's dashboard, go to Automation > Cloud Script and click on "Upload New Revision" at the top right corner.

Select the CloudScript.txt file included in SIS (SimpleIAPSystem > Scripts > Extensions > PlayFab) and check the box to make it live immediately after upload.



[yellowalert]You've made it to the end! As mentioned at the beginning, please note that development on the PlayFab integration is still in progress.
Your feedback on this guide or the integration in general would be much appreciated to further shape the direction of new features![/yellowalert]
« Last Edit: April 04, 2018, 07:42:35 pm by Baroni »