Upsight Ad Mediation

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.

Unity

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

Unity

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.

iOS

Cocoapods


The Upsight SDK and mediation library can be installed via cocoapods. To do so, simply add pod 'UpsightKit', '~> 4.2' and pod 'UpsightAdMediation', '~> 2.6' similar to the following in your Podfile:

target 'MyApp' do
  pod 'UpsightKit', '~> 4.2'
  pod 'UpsightAdMediation', '~> 2.6'
end

Then run a pod install inside your terminal, or from CocoaPods.app.

You can read more about our cocoapod on the UpsightKit page.

iOS

Manual Integration


Download the SDK

To begin, download the latest Upsight SDK.

Complete the following steps to integrate the base SDK and the ad mediation module:

  1. From the Upsight SDK folder, drag UpsightKit.framework into your Project’s Framework folder in the Xcode Navigator window. Ensure that UpsightKit.framework was added to the Build Phases section of the target settings. Then add CoreTelephony.framework and AdSupport.framework provided by Apple to the Build Phases section. Integration step 1

  2. Navigate to the 'Info' page of the project settings. Under 'Custom iOS Target Properties' create a key called UpsightAppToken with String as a Type and copy your Upsight App Token to the value field. Next create a key called UpsightPublicKey with String as a Type and copy your App Public Key as a string to the value field. These are provided on the Upsight dashboard under Settings > Applications > App Name. Integration step 2

  3. In the Build Settings section of the target, add -ObjC to the Other Linker Flags field. Integration step 3

    Note -ObjC tag is case sensitive.

  4. Download the Upsight Ad Mediation library.

  5. Import the Upsight Ad Mediation SDK into your project. Right Click YourProject > Add Files to "YourProject".

  6. Next browse to the location where you have uncompressed the SDK and select UpsightAdMediationSDK, on the same dialog, choose "Create groups". Now click "Add".

Once finished, your project should contain four additional files:

UpsightAdMediation.h
UpsightAdMediationDefinitions.h
libUpsightMediation.a
libUpsightMediationAds.a

Project Configuration

Required Frameworks

The Upsight Ad Mediation SDK requires these frameworks to be included in addition to the base frameworks required by the Upsight SDK:

  1. Accelerate.framework
  2. AudioToolbox.framework
  3. AVFoundation.framework
  4. CoreGraphics.framework
  5. CoreLocation.framework
  6. CoreMedia.framework
  7. EventKit.framework
  8. EventKitUI.framework
  9. Foundation.framework
  10. GameKit.framework
  11. iAd.framework
  12. libsqlite3.dylib
  13. libxml2.dylib
  14. libz.dylib
  15. MediaPlayer.framework
  16. MessageUI.framework
  17. MobileCoreServices.framework
  18. QuartzCore.framework
  19. Social.framework (weak link)
  20. StoreKit.framework
  21. SystemConfiguration.framework
  22. Twitter.framework
  23. UIKit.framework
  24. WebKit.framework

Disabling ATS and BitCode

AppTransportSecurity

Some of the ad network SDKs used by the Upsight Ad Mediation SDK do not support sending their data over HTTPS. If you are building on XCode 7, you must turn off App Transport Security by adding an additional dictionary item to your Info.plist. To so, add a dictionary item in your Info.plist called NSAppTransportSecurity with a boolean item NSAllowsArbitraryLoads set to YES. You can view more information this specific setting on Apple's documentation website.

BitCode

While the Upsight and UpsightAdMediation SDK are built with bitcode enabled, some of the included ad network libraries have not yet enabled bitcode. You can manually disable bitcode in your application by going to the Build Options in your target's build settings and setting Enable Bitcode to No.

iOS

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 two separate methods that you can use to track monetization. If you wish to track a purchase made through the App Store, use the following method from the Upsight class:

 + (void)recordInAppPurchaseEventWithResolution:(USPurchaseResolution)resolution
 product:(NSString *)product
 quantity:(NSUInteger)quantity
 price:(float)price
 currency:(NSString *)currency
 transactionIdentifier:(NSString *)transactionIdentifier;
  • resolution - one of:

    • USPurchaseResolutionBuy if the purchase was successful.
    • USPurchaseResolutionCancel if the user canceled the purchase.
  • product - The product name, as provided by the productIdentifier property of an SKProduct object.

  • quantity - The number of products purchased during the transaction, as set in the quantity property of an SKPayment object.

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

  • currency - the value returned by [priceLocale objectForKey:NSLocaleCurrencyCode] where priceLocale is the priceLocale of an SKProduct object.

  • transactionIdentifier - A value extracted from the SKTransaction object sent by Apple during the StoreKit exchange.

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 store, you can use this method instead:

+ (void)recordMonetizationEventWithTotalPrice:(float)totalPrice currency:
(NSString *)currency;
  • totalPrice - the total amount of the transaction.

  • currency - typically retrieved using [[NSLocale currentLocale] objectForKey:NSLocaleCurrencyCode].

iOS

Showing Mediated Video Ads


Milestones

Milestones track user movement through your app and allow you to manage exactly when and where a user sees 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 recordMilestoneEventForScope:@"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 NSDictionary:

[Upsight recordMilestoneEventForScope:@"main_menu" properties:@{ @"Age": @"42", @"Gender": @"Male"}];


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 as a response to a milestone call. 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 three basic steps to show content:

  1. Add the USBillboardDelegate protocol to one of your classes and implement presentingViewControllerForBillboard:
  2. Record a Milestone event for the scope.
  3. Get the USBillboard instance for the scope in which you want to show content, and set its delegate property to point at an instance of the class from step 1.

Important By changing when your code starts performing steps 2 and 3 above, you can control when your content will be shown. Steps 2 and 3 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 isContentReady method to check that content was delivered for a given milestone and is ready for display before even opening up a billboard.

[Upsight billboardForScope:scope].isContentReady;

Rewarded Video Ads - Handling Rewards

In the event your user receives a reward, you are notified through this optional method of the billboard delegate protocol:

- (void)billboard:(id<USBillboard>)aBillboard didReceiveReward:
(id<USReward>)aReward;

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 which is stored as a JSON NSData object by calling aReward.signatureData.

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 a python example of 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.

Android

Integration


The following steps outline the integration of the Upsight SDK for ad mediation.

First, add the Upsight repository to your application's build.gradle.

allprojects {
    repositories {
        maven {
            url "https://nexus.upsight.com/nexus/content/repositories/upsight-android-release/"
        }
        ...
    }
}

To include all the standard Upsight modules, add:

compile 'com.upsight.android:all:4.2.3'
compile 'com.upsight.android:mediation:4.2.3'

Add the following in your application Manifest. The application token and public key are provided on the Upsight Dashboard under Settings > Applications > "YOUR_APPLICATION_NAME".

<application>

    <!-- Application token and public key from Upsight Dashboard -->
    <meta-data
        android:name="com.upsight.app_token"
        android:value="UPSIGHT_APPLICATION_TOKEN" />
    <meta-data
        android:name="com.upsight.public_key"
        android:value="UPSIGHT_PUBLIC_KEY" />

    <!-- e.g. android:authorities="com.yourCompany.yourApplication.upsight" -->
    <provider
        android:name="com.upsight.android.internal.persistence.ContentProvider"
        android:authorities="APPLICATION_PACKAGE_NAME.upsight"
        android:enabled="true"
        android:exported="false" />
</application>

In order to access any API from the SDK, the application needs to build an UpsightContext. This should be done in the onCreate() of your Application or Activity, so we begin tracking the session appropriately:

public class SampleActivity extends Activity {

    private UpsightContext mUpsight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // Create an UpsightContext from any Android Context.
        mUpsight = Upsight.createContext(this);
        ...
    }
}

If you wish to enable logging, add the following:

mUpsight.getLogger().setLogLevel(Upsight.LOG_TAG, EnumSet.allOf(UpsightLogger.Level.class));

Tip: You may call Upsight.createContext(android.content.Context) anywhere in your application, and as often as you need a reference to UpsightContext. The same instance will be returned on each call.

Tip: You can use UpsightContext anywhere in your application where you currently use an android.content.Context. It provides extra functionality made available by the Upsight SDK.

Android

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.

If you wish to track an in-app purchase that is processed through the Google Play Store, use the following API from the UpsightGooglePlayHelper, which extracts receipt information for our servers to verify the transaction with Google:

UpsightGooglePlayHelper.trackPurchase(mUpsight, quantity, currency, price, totalPrice, product, responseData, publisherData);
  • mUpsight - The Upsight Context.

  • quantity - The number of products purchased during the transaction.

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

  • price - The price per unit in local currency.

  • totalPrice - The total price of the transaction, including fractional amounts of the currency, before store fees have been taken into account.

  • product - The product ID of the Google Play in-app product.

  • responseData - The purchase response data from onActivityResult(). See Google Play In-app Billing Version 3 API.

  • publisherData - Optional custom parameter bundle.

Note If you would like your IAP data to be validated, first upload your Google Play License Key to Upsight Dashboard.

App Settings Dashboard

This can be found by navigating to the Upsight Dashboard in the App Settings page. (Applications > YOUR_APPLICATION > App Settings > Edit App > Google Play License Key).

If you have a purchase to record that did not involve the Google Play store, you can use the following code below to record a Monetization Event, where no receipt verification will be performed:

UpsightMonetizationEvent
    .createBuilder(totalPrice, currency)  // Required event properties.
    .setProduct("product.name")           // Optional event property.
    .put(customBundle)                    // Custom property bundle.
    .put(customKey, customValue)          // Custom property override.
    .record(mUpsight);                    // Record event.

Android

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.

The client tells the server that the user has reached a specific milestone in the application, by recording an UpsightMilestoneEvent as below:

UpsightMilestoneEvent.createBuilder(scope).record(mUpsight);

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".


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

Billboards

Displaying marketing content requires a "Billboard". A Billboard is like an empty frame into which the SDK can place content it receives from the server in response to a Milestone. Like Milestone events, each Billboard is associated with a Scope. Upon receiving an event, the server will send marketing content applicable to the Scope of that Milestone, which are eligible for the Billboard with matching Scope. This allows for control of when and where the content is created.

To create a Billboard, add the following to the onResume() of an Activity or Fragment:

UpsightBillboard.Handler handler = UpsightBillboardHandlers.forDefault(activity);
UpsightBillboard billboard = UpsightBillboard.create(mUpsight, scope, handler);

The Billboard created should be destroyed in the onPause() by calling billboard.destroy() to avoid unintended UI transitions. You cannot create two Billboards with the same scope unless the first one has been destroyed, or it has completed the lifecycle of displaying a unit of marketing content, in which case it is unregistered by the system and its handler.onDetach() callback has occurred.

The handler allows the client to be notified of Billboard lifecycle events when an eligible marketing content becomes available. The UpsightBillboardHandlers class provides default implementations, but the client may provide custom implementations by subclassing the defaults, or directly implementing the UpsightBillboard.Handler interface. For example, the client may wish to temporarily disable a Billboard. To accomplish this, return null when handler.onAttach() is called to skip over any marketing content that becomes available during that time.

Additionally, if you would like to check that content is ready to display before opening a billboard, you can use the isContentReady method. This method will only return true if milestone is invoked with the corresponding scope and content has been received from the server.

UpsightMarketingContentStore.isContentReady(mUpsight, scope)

Tip: The permission requirement android.permission.INTERNET is automatically merged to your application Manifest.

Rewarded Video Ads - Handling Rewards

In the event your user receives a reward, you are notified through this optional method from the UpsightBillboard.Handler:

void onRewards(List<UpsightReward> rewards);

By providing an implementation for this method, your code is given the opportunity to take appropriate action based on your user completing a rewarded video ad.

See below for a sample implementation of the onRewards methods.

private static class MyBillboardHandler extends UpsightBillboardHandlers.DefaultHandler {

    private final Context mContext;

    private MyBillboardHandler(Activity activity) {
        super(activity);

        // It is important that you do not keep a strong reference to the Activity, but only use
        // the Application Context in your callback implementations, because there is no
        // guarantee the current Activity will be present when these callbacks are triggered.
        mContext = activity.getApplicationContext();
    }

    @Override
    public void onRewards(List<UpsightReward> list) {
        for (UpsightReward reward : list) {
            String text = "Reward received: " + reward.getProduct() + " x " + reward.getQuantity();
            Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
        }
    }
}

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 JSON by calling UpsightReward.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 a python example of 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.

Dashboard Setup

Dashboard Setup

Adding Milestones


Adding Milestones

Mediated ads will be triggered by recording a milestone, followed by preparing a billboard. The milestone scope names that are being called in the app must also be added for your application in the Upsight dashboard.

To add milestones, navigate to the "Application" menu.

Application Menu

Choose your app, and select "Milestones" from the right side menu. Next, click "Add Milestone".

Milestone Landing

Enter the milestone scope name, and a description. Click "Save".

Add Milestone

You'll now see the newly added milestone as a possible option when creating a new mediated ad campaign.

Dashboard Setup

Adding Rewards


Adding Rewards

When using mediated rewarded videos, you'll need to have one or more reward items set up in the dashboard. The SDK will return the reward names and quantities through the reward callback when the video ad view has completed.

To add rewards, navigate to the "Application" menu.

Application Menu

Choose your app, and select "Rewards" from the right side menu. Next, click "Add Reward".

Reward Landing

Enter the reward scope name, and a description. You can also set a min and max app version that this reward applies to. Click "Save".

Add Reward

You'll now be able to choose your newly added reward items when creating a rewarded video campaign, and dynamically grant multiple items, with multiple quantities, on a per segment basis.

Dashboard Setup

Creating Segments


Creating Segments

Mediated ad campaigns can be targeted at segments of your users. Segments can be created based on a number of different user attributes, including IAP purchase behaviour.

User Explorer

The User Explorer interface allows you to build segments by selecting sub-sets of attribute data. As you focus on specific attributes, you can see the user count (as well as percentage of total users) update in real-time.

User Explorer

Click "Save Segment". Add a name and description for the segment, and any more rules if needed.

New Segment

Your new segment can now be selected for targeting in your marketing campaigns.

Dashboard Setup

Creating Mediated Ad Campaigns


Creating Mediated Ad Campaigns

Once you have added your milestones, and reward items (as applicable), you can now create campaigns for your app that will display mediated static interstitial, non-rewarded video or rewarded video ads.

To create a campaign, navigate to the "Campaigns" page in the Upsight dashboard, and click "Add A New Campaign".

Campaign Landing

Choose "Ads" as the campaign type.

Select Campaign Type

Enter a campaign name, and select an app. You'll be able to choose a segment ("All Users" is targeted by default), and choose the milestones that this campaign will target.

Campaign App Selection and Targeting

Choose the ad type. Selecting "Video" with the reward toggle turned off will return non-rewarded videos. Selecting Interstitial will return static interstitial ads. Selecting "Video" with the reward toggle turned on will return rewarded video ads.

Select Ad Type

For rewarded video ads, you can choose the reward item(s) that you've previously added for your app. Adjust the quantities as necessary.

Rewarded Video Rewards

For rewarded video ads, you can also choose whether you want to show a pre or post roll message. The pre-roll message is typically used when rewarded ads are presented in an interstitial type flow (i.e. not triggered by the user tapping a button). Both messages are optional, and can be localized for supporting multiple languages if required.

Rewarded Video Pre and Post Roll Messages

Click "Save and Pause" to test the campaign using your test devices. Click "Save and Publish" if you would like the campaign to be live for your users.

You can now see all your campaigns listed. Statistics for campaigns will begin to appear approximately one day following them going live, with stats updated on a daily basis.

Campaign List

You can adjust the priority of your campaigns by navigating to the "Campaign Priority" page. Select an app and milestone, and simply drag the campaigns into whichever priority order is best for your needs. Users will progress through the waterfall receiving the first listed campaign that they qualify for (are in the targeted segment, and have not exceeded any frequency caps).

Campaign Priority