Unity

Integration


Downloading the SDK

To integrate Upsight Ad Mediation, you'll need to download the latest Upsight Unity SDK version 4.1 or later.

Importing

Integrating Upsight's Unity SDK is done through a few simple steps:

  1. Open up your Unity project and double-click the Upsight unitypackage to import it into your project

  2. Switch to either the iOS or Android platform from the build settings menu.

  3. In the Upsight Dashboard under Settings > Applications > App Name locate your App Token and Public Key.

  4. In Unity, under Tools > Upsight, open the Configuration Wizard and add in your App Token and Public Key for your desired platform.

    Configuration Wizard

  5. Create a new script attached to your main scene, calling Upsight.init()

  6. You can now build your application

Please note that Upsight Ad Mediation is enabled by default.

Important On Android, please ensure that the Write Access is set to external (sdcard) within Unity's Player Settings as Upsight Ad Mediation requires this permission to serve ads on older versions of Android and to serve ads quickly on newer versions. This permission will automatically be added if you use the Upsight-provided build tools.

Building

On Android your application may hit the method count (dex) limit. In this case, please follow our proguard steps.

For iOS there are no additional steps required to build.

Tracking Paying Users


Tracking Paying Users

Upsight offers you the ability to track in-app purchase events, which not only provides you with revenue data in your dashboards, but also allows you to segment your users based on their spending behaviours.

There are three separate methods that you can use to track monetization.

If you wish to track a purchase made through the Google Play Store, use the following methods:

  Upsight.recordGooglePlayPurchase(quantity, currency, price, totalPrice, product, responseCode, inAppPurchaseData, inAppDataSignature, properties)
  • quantity - The number of products purchased during the transaction, as set in the quantity property of an SKPayment object or Google Equivalent.

  • currency - The currency as a 3-character ISO 4217 code.

  • price - The price of the product.

  • totalPrice - the total price of the transaction.

  • product - The product name.

  • responseCode - The value mapped to the RESPONSE_CODE in the purchase response data from onActivityResult. See Google Play In-app Billing Version 3 API.

  • inAppPurchaseData - The value mapped to the INAPP_PURCHASE_DATA in the purchase response data from onActivityResult. See Google Play In-app Billing Version 3 API.

  • inAppDataSignature - The value mapped to the INAPP_DATA_SIGNATURE in the purchase response data from onActivityResult. See Google Play In-app Billing Version 3 API.

  • properties - (optional) a dictionary of custom properties to send to the server for use in DataMine.

If you wish to track a purchase made through the iOS App Store, use the following methods:

  Upsight.recordAppleStorePurchase(quantity, currency, price, transactionIdentifier, product, UpsightPurchaseResolution, properties)
  • quantity - The number of products purchased during the transaction, as set in the quantity property of an SKPayment object or Google Equivalent.

  • currency - The currency used to make the purchase.

  • price - The value returned by price.floatValue where price is the price property of an SKProduct object or Google Equivalent.

  • transactionIdentifier - The Transaction ID, as provided by the transactionIdentifier property of an SKProduct.

  • product - The product name, as provided by the productIdentifier property of an SKProduct.

  • UpsightPurchaseResoltuion - one of:

    • UpsightPurchaseResolution.Buy if the purchase was successful.
    • UpsightPurchaseResolution.Cancel if the user canceled the purchase.
  • properties - (optional) a dictionary of custom properties to send to the server for use in DataMine.

When the SDK sends an InAppPurchase event recorded with this method, it attaches the receipt object from the transaction with the App Store. The Upsight server then validates this receipt with the Apple servers.

If you have a purchase to record that did not involve the Apple or Google Play store, you can use this method instead:

Upsight.recordMonetizationEvent(totalPrice, currency, UpsightPurchaseResolution, product, price, quantity, properties)
  • totalPrice - the total amount of the transaction.

  • currency - the currency used to make the purchase

  • UpsightPurchaseResoltuion - one of:

    • UpsightPurchaseResolution.Buy if the purchase was successful.
    • UpsightPurchaseResolution.Cancel if the user canceled the purchase.
  • product - (optional) the identifier of the product purchased

  • price - (optional) the per-unit price of the purchase

  • quantity - (optional) the number of units purchased

  • properties - (optional) a dictionary of custom properties to send to the for use in DataMine

Showing Mediated Video Ads


Milestones

Milestones track user movement through your app and allow you to manage exactly when and where a user sees marketing content, including mediated ads. Milestones are triggered when your user reaches a point in your application that you want to track or take action on. After a user hits a Milestone of a given scope, the user will be able to see content from an open Billboard that also has that same scope.

To set a milestone, simply call the following function and assign a scope:

Upsight.recordMilestoneEvent ("main_menu");

Milestones have one required property - a "Scope" that uniquely describes that location in your application. Examples of Scope are "main_menu", "inventory", or "level_up". Additionally Milestone can track event properties by using a Dictionary:

var properties = new Dictionary<string, object> ();
properties.Add ("Age", "42");
properties.Add ("Gender", "Male");

Upsight.recordMilestoneEvent ("event_name", properties);


Important Milestones must also be setup in the Upsight dashboard. See Dashboard Setup for instructions.

Billboards

In order to display marketing content, a 'Billboard' must exist and be open. A billboard is like an empty frame into which the SDK can place content it receives from the server. Like milestone events, each billboard is associated with a Scope. The content returned after a Milestone event will have the same Scope as the Milestone.

There are two basic steps to showing content:

  1. Record a Milestone event for the scope. This delivers content to your device to be shown when a billboard is open.
  2. Call Upsight.prepareBillboard ("scope"); to prepare a billboard for the given scope. This allows any content delivered for that scope to be shown.

Note The Upsight Unity SDK plugin only allows one billboard to be shown at a time. When you create an additional billboard, all previous billboards will be removed.

Important By changing when your code starts performing steps 1 and 2 above, you can control when your content will be shown. Steps 1 and 2 do not need to be performed in a particular order, and content won't be shown until both steps have been performed. This allows you to control content freely. Additionally, you can use the isContentReadyForBillboardWithScope method to check that content is ready for display before even opening up a billboard. isContentReadyForBillboardWithScope will only return true after a milestone of the same scope has been called.

Upsight.isContentReadyForBillboardWithScope( string scope )

Rewarded Video Ads - Handling Rewards

To handle a reward granted to a user for watching a rewarded video ad, you can listen to the reward callback by registering your own method to be invoked when they occur:

UpsightManager.billboardDidReceiveRewardEvent += myRewardMethod;

This method passes in a UpsightReward object:

void myRewardMethod(UpsightReward reward) {
  // track granting the reward using the UpsightReward object
}

Validating Rewards

If you would like to validate the reward that the Upsight server has granted to the device, you can do so by sending reward signature data to your server and performing an operation on the contents. You can get the signature data for a reward by calling reward.getSignatureData().

This JSON object contains the product, sid, quantity, nonce, and signature of the reward. You use the product, sid, quantity, and nonce along with your app's secret_key to produce the signature provided in the payload on your server.

Below is an example of python reward verification:

import base64
import hashlib
import hmac


def validate_signature_data(signature_data, secret):
    """Validates the signature for Upsight rewards.

    >>> secret = 'YOUR_32_CHAR_SECRET_KEY'
    >>> signature_data = {
    ...     'idfv': 'AAAAAAAA-0000-0000-0000-000000000000',
    ...     'nonce': '0437121572:rambo_cat:1',
    ...     'product': 'rambo_cat',
    ...     'quantity': 1,
    ...     'sid': '10000000000000000000',
    ...     'sig4': 'joQiupsyEe10Ui83TCPuScVBfOo',
    ...     'token': 'YOUR_APP_TOKEN'
    ... }
    >>> validate_signature_data(signature_data, secret)

    If the signature is invalid, or there is a problem with the signature_data
    dictionary, ValueError will be raised:

    >>> signature_data['sig4'] = 'invalid'
    >>> validate_signature_data(signature_data, secret)
    Traceback (most recent call last):
      ...
    ValueError: incorrect signature

    :param dict signature_data: A dictionary of signature data, from the SDK.
    :param str secret: Your app secret string.
    :raises ValueError: if the signature is invalid.
    """
    for required in ('nonce', 'sig4', 'token'):
        if required not in signature_data:
            raise ValueError('signature_data is missing {}'.format(required))

    identifiers = {}
    for identifier in ('device', 'gid', 'ifa', 'mac', 'odid', 'odin',
                       'idfv', 'sid'):
        value = signature_data.get(identifier)
        if not value:
            continue
        if isinstance(value, unicode):
            value = value.encode('utf8')
        identifiers[identifier] = value
    if not identifiers:
        raise ValueError('signature_data is missing identifiers')

    message = ':'.join((':'.join(str(identifiers[key])
                                 for key in sorted(identifiers.keys())),
                        signature_data['token'],
                        signature_data['nonce']))
    signature_hash = hmac.new(str(secret), message, hashlib.sha1)
    signature = base64.urlsafe_b64encode(signature_hash.digest()).rstrip('=')
    if not hmac.compare_digest(signature_data['sig4'], signature):
        raise ValueError('incorrect signature')

Dashboard Setup

In order to trigger ads in your app, you'll need to add milestones and rewards to your application settings in the Upsight dashboard, and create static interstitial, non-rewarded video, or rewarded video campaigns. See the Dashboard Setup section for details.