Skip to content

SDK implementation

amironicheva edited this page Feb 26, 2020 · 98 revisions

The SDK is not supported if the app launches in Unity Editor.

On the previous steps, we added the SDK to a project and made a connection to gameofwhales.com. Now we are ready to implement the SDK. Do the following steps for this.

Pay attention that the SDK will ask the following permissions on the Android user's device:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

NOTE about Android X: if your project uses the libraries for Android X, download com.gameofwhales.sdkx-<version>.aar library, remove com.gameofwhales.sdk-<version>.aar from your project and add com.gameofwhales.sdkx-<version>.aar. <version> is the number of used SDK version. It's supported since 2.0.32 version of SDK.

Initialization

Step 1

Init the GOW SDK when you start your app.

If you use Unity In-App Purchasing service you can do the initialization like this:

    GameOfWhales.OnInitialized += OnGameOfWhalesInitialized;(Optional)
    GameOfWhales.OnConnected += OnGameOfWhalesConnected;(Optional)
    
    GameOfWhales.Init(GameOfWhales.GetCurrentStore());

The subscription to OnGameOfWhalesInitialized is needed just if you want to get information that the SDK has been initialized.

OnConnected is called after the GOW server response with dataReceived: true. If there was no response from the GOW server, there was an error during the request to the server or the game is offline, dataReceived is false. OnConnected callback is supported since 2.0.32 version of SDK.

In other cases, you should specify the default store manually. For example:

   #if UNITY_IOS
        string store = GameOfWhales.STORE_APPLEAPPSTORE;
   #else
        // any value from the list: STORE_GOOGLEPLAY, STORE_SAMSUNG     
        string store = GameOfWhales.STORE_GOOGLEPLAY;
   #endif
        
        GameOfWhales.Init(store);

GDPR NOTE: By default, the SDK uses advertisement ID (IDFA) as a user ID to send events to Game of Whales server. In order to work in a non-personal mode when a random value will be used as a user ID, the SDK should be initialized as follows:

   bool nonPersonal = true;
   GameOfWhales.Init(GameOfWhales.STORE_GOOGLEPLAY, nonPersonal);

The random value will be defined for the first event and it will be kept for all events until the game is removed/re-installed from the device.

Purchases

Step 2

Purchases with verification on GOW server side

Check that Android Bundle Identifier and Android Public License Key (for Android app) and iOS Bundle Identifier (for iOS app) have been filled on Game Settings page before you will make a purchase.

Pay attention! Game of Whales doesn't support purchases from Unity editor directly.

To send information about purchases to Game of Whales, add InAppPurchased call when you make a purchase.

PurchaseProcessingResult IStoreListener.ProcessPurchase(PurchaseEventArgs e)
  {
      GameOfWhales.InAppPurchased(
            e.purchasedProduct.definition.id,
            (float)e.purchasedProduct.metadata.localizedPrice,
            e.purchasedProduct.metadata.isoCurrencyCode,
            e.purchasedProduct.transactionID,
            e.purchasedProduct.receipt);
  }

If you don't use Unity IAP Service you need creating receipt value in the special format.

If you want to use Game of Whales for purchases validation, subscribe to the following events:

  void Start()
  {
      GameOfWhales.OnPurchaseVerified += OnPurchaseVerified;
  }

The verify state can be:

  • VERIFY_STATE_LEGAL - a purchase is normal.
  • VERIFY_STATE_ILLEGAL - a purchase is a cheater's.
  • VERIFY_STATE_UNDEFINED - GOW server couldn't define the state of purchase. 

Purchases without verification on GOW server side

The method is available since v.2.0.24 SDK version

In order to send information about purchases without verification on Game of Whales side, call Purchase method. For example:

	string productID = "product_10";
	string currency = "USD";
	double price = 1.99;
	    
	GameOfWhales.Purchase(productID, currency, price * 100);

Pay attention that all purchases received through Purchase method (including refunds, restores, cheater's purchases) will increase the stats. So in order to have correct stats, a game developer should verify purchases on the game side and send the data only about legal purchases to Game of Whales system.

Special Offers

You need to do this chapter steps only if you want to use special offers from Game of Whales in your app.

Step 3

Before any product can be used in a special offer it has to be bought by someone after SDK has been implemented into the game. Please make sure your game has at least one purchase of the product that is going to be used in the special offer. If you want to create a special offer for an in-game resource, please, make sure your game has at least one converting event with the appropriate resource.

In order to receive the information regarding special offers' availability, subscribe to the following events when the application is initialized:

        GameOfWhales.OnSpecialOfferAppeared += OnOfferAppeared;
        GameOfWhales.OnSpecialOfferedDisappeared += OnOfferDisappeared;

In order to get the data about anti-churn offers, subscribe to the following event when the application is initialized:

        GameOfWhales.Instance.OnFutureSpecialOfferAppeared += OnFutureSpecialOfferAppeared;

Pay attention that the subscriptions are not supported if you launch the app from Unity editor.

You should decide what you want to do with the offer if the appropriate event has happened. For example, once OnOfferDisappeared event is received, you should remove all the graphical indications for the special offer from the game.

In order to receive special offer call the following method:

    SpecialOffer offer = GameOfWhales.GetSpecialOffer(id);
    if (offer != null)
    { ....

Special offer can influence a product's price(except in-app purchases):

if (offer.HasPriceFactor())
  {
    price *= offer.priceFactor;
  }

Special offer can also influence count (count of coins, for example) which a player receives by purchase:

  if (offer.HasCountFactor())
  {
    coins *= offer.countFactor;
  }

It's possible to pass custom data to special offers. In order to get the data in the game's side, use customValues parameter of SpecialOffer class.

   string str = offer.customValues["your_string"].ToString();
   int number = int.Parse (offer.customValues["your_int"].ToString());
   bool boolean = bool.Parse (offer.customValues["your_bool"].ToString());

Notifications

You need to do this chapter steps only if you want to receive push notifications from Game of Whales in your app.

Step 4 (only if you use Firebase or Google Cloud Messaging)

Register your project in the Firebase console.

Step 5 (only if you use Firebase)

Add Firebase to your Unity Project and register your firebase token in the SDK when you are getting it.

public void OnTokenReceived(object sender,
              Firebase.Messaging.TokenReceivedEventArgs token) {
        Debug.Log("Received Registration Token: " + token.Token);
        //register your token at SDK
         GameOfWhales.UpdateToken(token, GameOfWhales.PROVIDER_FCM);
        }

Step 6 (only if you use Google Cloud Messaging)

Open GameOfWhalesSettings form (in the Unity editor menu: go to Window >> Game of Whales) and enter Android Project ID which will be used to get a token. You can also specify Firebase Sender ID instead of Android Project ID.

If you don't use "Google Cloud Messaging" leave the "Android Project ID" field on the Unity settings as blank.

Check that the following libraries were added to your android project:

play-services-base-xxx.aar
play-services-basement-xxx.aar
play-services-gcm-xxx.aar
play-services-identity-xxx.aar
play-services-iid-xxx.aar
play-services-tasks-xxx.aar
support-v4-yyy.aar

Step 7 (for iOS only)

Enable the Push Notifications option in the Xcode.

If you are building your iOS project with unity cloud build, you need to enable Remote Push Notification Capability.

Step 8 (for iOS only)

Call RegisterForNotifications() method in any place of your app where the user should approve receiving notifications.

    GameOfWhales.RegisterForNotifications();

Step 9 (for Android only)

Add a receiver to send the information about notifications to your manifest and specify your Android Bundle Identifier instead of APP_BUNDLE.

     <receiver
        android:name="com.gameofwhales.sdk.util.GOWBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
               <action android:name="com.google.android.c2dm.intent.RECEIVE" />
               <category android:name="APP_BUNDLE"/>
            </intent-filter>
        </receiver>
     
     ...
     </application>

Add the next permissions to your manifest and specify your Android Bundle Identifier instead APP_BUNDLE.

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="APP_BUNDLE.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="APP_BUNDLE.permission.C2D_MESSAGE" />

If you haven't had an android manifest in your project yet, you can use GOWAndroidManifest.xml from SDK, but you need renaming of it to AndroidManifest.xml and replace APP_BUNDLE to your Android Bundle Identifier wherever it is defined.

Step 10

In order to send the information to Game of Whales regarding a player's reaction on a push notification (to increase push campaign's Reacted field) of an already started app call the following method:

GameOfWhales.OnPushDelivered += OnPushDelivered;
...
private void OnPushDelivered(SpecialOffer offer, string campID, string title, string message)
    {
    	//Show the notification to a player and then call the following method
        GameOfWhales.PushReacted(campID);
    }

Step 11

In order to enable or disable push notifications, use the following method:

	GameOfWhales.SetPushNotificationsEnable(false);

Step 12 Rich notifications on iOS devices (optional)

Pay attention that this step is actual only for Unity 2017.

If you want to send push notifications with images on iOS devices, you need to do the following steps:

  • Open GameOfWhalesSettings form in Unity project (go to Window >> Game of Whales) and check Notification Service option.
  • Create a certificate for {your_app_id}.notificationservice bundle.
  • Specify extension's bundle id in Bundle postfix field of GameOfWhalesSettings form in Unity project.
  • Generate XCODE project by using Unity. Notification Service Extension will be automatically added to the project.

Make sure that deployment target is 10 because in some cases Notification Service Extension does not work on devices with the iOS version less than deployment target version.

In order to check notifications implementation send a test notification.

Profiles

Step 13

You can send additional data about your players by using the Profile method. Profile method should be called if key parameters of your app or a player have changed.

If you send more than 3000 properties, Game of Whales will sort all properties alphabetically and will save only the first 3000.

If the length of a string-type property is more than 64 characters, Game of Whales will save only the first 64 characters.

For example:

GameOfWhales.Profile(new Dictionary<string, object> {
	            {"coins", coins},
	            {"class", userClass},
	            {"gender", gender},
	            {"location", location},
	            {"level", level}
	        });

Converting

Step 14

If you are going to use AI offers functionality you need to send to Game of Whales information about players' game activity by using Converting method. Converting method should be called to show what exactly the player spent and what he got instead of spent resources. Read more...

For example:

Someone bought one bike_1 for 1000 coins and 50 gas. You should call the following method to reflect this operation in Game of Whales:

GameOfWhales.Converting(new Dictionary<string, int> {
            {"coins", -1000},
            {"gas", -50},
            {"bike_1", 1}
        }, "shop");

Another sample: someone bought the main pack for $5. It was an in-app purchase with mainPack SKU. The pack included 100 coins and 1 bike. In order to send the data that the player got 100 coins and 1 bike after the purchase of mainPack to Game of Whales, the following Converting method should be called:

GameOfWhales.Converting(new Dictionary<string, int> {
            {"mainPack", -1},
            {"coin", 100},
            {"bike", 1}
        }, "shop");

There are 2 additional methods that can be used instead of Converting method:

  • Consume - to show that a player spends a certain amount of one resource for the purchase of a quantity of another resource.

For example:

    GameOfWhales.Consume("coins", 1000, "gas", 50, "shop");

It means that someone spent 1000 "coins" for 50 "gas" in "shop".

  • Acquire - to show that a player acquires a certain amount of one resource and spends a quantity of another resource. The method can be used for in-app and in game items. It's important to call acquire method for in-app items after InAppPurchased. For example:
   GameOfWhales.Acquire("coins", 10000, sku, 1, "bank");

It means that someone has acquired 10000 "coins" for 1 "sku" in "bank".

Consume and Acquire methods can be called when one resource is changed to another resource. In more complicated cases (for example, when one resource is spent for several types of resources) Converting method should be called.

Cross promotion ads

It's supported since version 2.0.20 of SDK for Unity.

To handle the ads set in Game of Whales, you need to do some actions:

Step 15

Subscribe to the following events to get the information about the current state of the ads:

	GameOfWhales.OnAdClosed += OnAdClosed;
        GameOfWhales.OnAdLoadFailed += OnAdLoadFailed;
        GameOfWhales.OnAdLoaded += OnAdLoaded;

Step 16

Start to load the ads at any place of your code (for example, during the launch of the game):

	GameOfWhales.LoadAd();

Step 17

Add the following code to the part of your game where you want to show the ads:

	if (GameOfWhales.IsAdLoaded())
        {
            GameOfWhales.ShowAd();
        }
	else
	{
            GameOfWhales.LoadAd();
	}

Profile's properties

Step 18

You can get some profile's properties defined on Game of Whales side via SDK.

For example, you can get the profile's property group by using the following code:

	var properties = GameOfWhales.GetProperties();
	if (properties.ContainsKey("group"))
	{
	    var group = properties["group"] as string;
	}

You can also receive the profile's group by using the special method:

	var group = GameOfWhales.GetUserGroup();

A/B testing (experiments)

It's supported since version 2.0.29 of SDK for Unity.

Step 19

In order to start working with experiments, it's needed to be subscribed to the following events:

     GameOfWhales.SetStartExperimentDelegate(CanStartExperiment);
     GameOfWhales.OnExperimentEnded += OnExperimentEnded;

In order to confirm that the player should take part in the experiment, it's needed to return true in experiment delegate:

   public bool CanStartExperiment(Experiment experiment)
   {
   	//Read experiment.payload, apply changes for experiment and return `true` if changes were applied
	return true;
   }

In order to check if there is an experiment at the start of the application, subscribe to OnConnected callback (see Step 1). If the experiment exists, CanStartExperiment delegate will be called before OnConnected.

When the experiment is finished, OnExperimentEnded method will be called. You are able to remove all experiment changes or keep them for further work regardless of the experiment:

  private void OnExperimentEnded(Experiment experiment)
  {
       //Remove experiment changes or keep them
  }

You can find code examples here.

Pay attention that the SDK sends immediately only "login" and "purchase" events. Other events ("token", "profile", etc) are collected in the bulk and sent time by time.