Skip to content
This repository has been archived by the owner on Jan 5, 2024. It is now read-only.

Showing Rewarded Interstitial Ads

Sebastian Markowski edited this page Mar 10, 2022 · 43 revisions

In general, the process and API for showing a rewarded interstitial ad is the same as for our interstitial ads. Below are any additional instructions/options for our rewarded interstitials.

Configuring Zone for Rewards

As shown below, ensure the zone you wish to show rewarded ads from is set to V4VC on the AdColony dashboard: AdColony V4VC Zone Config

Listen For Reward Events

Within the configure success callback, add a reward callback to the appropriate zones.

/* Objective C */

NSArray<String *> *rewardedZones = @[/* Rewarded Zone IDs */]
__weak typeof(self) weakSelf = self;
[AdColony configureWithAppID:/* App ID */ options:appOptions completion:^(NSArray<AdColonyZone *> *zones) {
    for (AdColonyZone *zone in zones) {
        if ([rewardedZones indexOfObjectIdenticalTo:zone.identifier] != NSNotFound) {
            zone.reward = ^(BOOL success, NSString * _Nonnull name, int amount) {
                if (success) {
                    __strong typeof(weakSelf) self = weakSelf;
                    [self rewardUserWithCoinsAmount:amount andCurrencyName:name];
                }
            }
        }
    }
}];
/* Swift */

let rewardedZones:Array<String> = [/* Rewarded Zone IDs */]
AdColony.configure(withAppID: /* App ID */, options: nil) { [weak self] (zones) in
    for zone in zones {
        if rewardedZones.contains(zone.identifier) {
            zone?.setReward = { [weak self] (success, name, amount) in
                if success {
                    self?.rewardUser(coinsAmount: amount, currencyName: name)
                }
            }
        }
    }
}

Rewarded App Options

If you would like to set a custom user id to be passed to your server for reward verification, you can set this via the AdColonyAppOptions object when configure is called initially at app launch:

/* Objective C */

AdColonyAppOptions *appOptions = [AdColonyAppOptions new];
appOptions.userID = @"newuserid";

// Pass options with user id set with configure
[AdColony configureWithAppID:/* App ID */ 
                     options:appOptions
                  completion:^(NSArray<AdColonyZone *> *zones) {
                      // ...
                  }
];
/* Swift */

let appOptions = AdColonyAppOptions()
appOptions.userID = "newuserid"

// Pass options with user id set with configure
AdColony.configure(withAppID: /* App ID */, options: appOptions) { [weak self] (zones) in
    // ...
}

If the user id changes at runtime (for example, if a new user logs in) you can update this information via the setAppOptions:

/* Objective-C */

// Get current AdColonyAppOptions and change user id
AdColonyAppOptions *appOptions = [AdColonyAppOptions new];
appOptions.userID = @"newuserid";

// Send new information to AdColony
[AdColony setAppOptions:appOptions];
/* Swift */

// Get current AdColonyAppOptions and change user id
let appOptions = AdColonyAppOptions()
appOptions.userID = "newuserid"

// Send new information to AdColony
AdColony.setAppOptions(appOptions)

Rewarded Ad Options

If you would like to use our reward confirmation/results dialogs, you can send in this information via the AdColonyAdOptions object when the ad request is made:

/* Objective C */

// Pass in options object when ad request is made
AdColonyAdOptions *options = [AdColonyAdOptions new];
options.showPrePopup = YES;
options.showPostPopup = YES;

[AdColony requestInterstitialInZone:/*Zone ID*/ options:option andDelegate:self];
/* Swift */

// Pass in options object when ad request is made
let options = AdColonyAdOptions()
options.showPrePopup = true
options.showPostPopup = true

AdColony.requestInterstitial(inZone: Ads.shared.currentZone, options: options, andDelegate: self)

Server-Side Rewards

To provide security for your virtual currency economy, AdColony issues callbacks which use message hashing for security directly to your servers that handle your virtual currency. In order to reward your users with the virtual currency rewarded by AdColony, you should create a callback URL on your game’s server system. AdColony will pass URL parameters to your game’s server via this URL, which are then used to update a user’s virtual currency balance in your system.

In AdColony we have an option to enable client­-side handling of virtual currency. Please note that use of this option is not advised because there is no way to create a secure client-­side virtual currency system. While we do our best to obfuscate our client­-side system, it is not possible to ensure its security. If you are unable to use a server to manage your virtual currency system, contact support@adcolony.com for usage guidelines.

Step 1 - Configuring Your Zone for Server-side Rewards

To enable server-side rewards for your zone, you must disable the client-side setting in our portal. Please see below:

Server-side Zone Config

Step 2 - Creating a callback URL

You must create a URL on your servers to receive the AdColony callback. The callback URL must not require any authentication to reach your server. Note that this does not mean your callback URL cannot be over HTTPS. It just means there must not be a login (or something to that effect) via header or otherwise.

You must make your URL respond appropriately to the AdColony callback. The format of the URL that AdColony will call is as follows, where brackets indicate strings that will vary based on your application and the details of the transaction:

[http://www .yourserver.com/anypath/callback_url.php]?id=[ID]&uid=[UID]&zone=[ZONE_ID]&amount=[CURRENCY_AMOUNT]&currency=[CURRENCY_TYPE]&verifier=[HASH]&open_udid=[OPEN_UDID]&udid=[UDID]&odin1=[ODIN1]&mac_sha1=[MAC_SHA1]

Note that open_udid, udid, odin1, and mac_sha1 will always be empty on Android. If your application provides a custom user ID to AdColony (see Rewarded App Options above), you will need to add &custom_id=[CUSTOM_ID] to the end your zone’s callback URL or it will not be provided to your server. You will also need to append the custom ID to the end of your test string before hashing and checking against your verifier.

The CUSTOM_ID field mentioned in the callback is populated from the AppOption's UserId field. The UID field is an internal id.

Once you have chosen this URL, you should input it in the video zone configuration page on the Control Panel.

Server-side Zone Config

Step 3 - Handling the AdColony Callbacks

You can use any server side language that supports an MD5 hash check to respond to URL requests on your server.

Even though it is not necessary to use PHP for your callback URL, for your convenience, the following PHP with MySQL sample code illustrates how to access the URL parameters, perform an MD5 hash check, check for duplicate transactions, and how to respond appropriately from the URL:

<?php

define('SECRET_KEY',  'Thiscomesfromadcolony.com');

define('DB_DSN',      'mysql:dbname=testdb;host=127.0.0.1');
define('DB_USER',     'user');
define('DB_PASSWORD', 'secretdbpassword');

/**
 * Fetch named $_GET argument safe way
 * @param string $name argument name
 * @return string
 */
function value($name) {
    if (isset($_GET[$name]) && is_string($_GET[$name])) {
        return $_GET[$name];
    }
    return '';
}

/**
 * Response with error and end script
 * @param string $reason failure reason
 * @param bool $internalError whenever it's fatal internal error
 */
function error($reason, $internalError = false) {
    if ($internalError) {
        // log fatal error reason
        //log_error("Error handling reward request: {$reason}")
        header('HTTP/1.0 500 Internal error');
    } else {
        //log_debug("Reward request failed: {$reason}")
        echo 'vc_declined';
    }
    exit;
}

/**
 * Fetch user id bound to device identifier
 * @param PDO $connection PDO connection object
 * @param string $deviceId device identifier
 * @return string|false user identifier or false if not found
 */
function userIdFromDeviceId($connection, $deviceId) {
    // internally fetch user id, for example:
    //return $connection->query('..')->fetchColumn();
    return false;
}


// fetch GET request arguments
$id       = value('id');
$deviceId = value('uid');
$amount   = value('amount');
$currency = value('currency');
$verifier = value('verifier');
$customId = value('custom_id');

// build verification string (md5 hash from GET arguments and SECRET_KEY salt)
$secret   = constant('SECRET_KEY');
$test     = md5("{$id}{$deviceId}{$amount}{$currency}{$secret}{$customId}");

// check whether verifier string matches one built internally
if ($test !== $verifier) {
    error('Verification failed');
}

// connect to database
try {
    $connection = new PDO(DB_DSN, DB_USER, DB_PASSWORD, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
} catch (PDOException $e) {
    error($e->getMessage(), true);
}

// fetch user id bound to device id
$userId = userIdFromDeviceId($connection, $deviceId); // get your internal user id from device id
if (!$userId) {
    error("Can't find user with device {$deviceId}");
}

// save transaction in database
try {
    $stmt = $connection->prepare('INSERT INTO AdColony_Transactions(`id`,`amount`,`name`,`user_id`,`time`) VALUES(?,?,?,?,CURRENT_TIMESTAMP())');
    if ($stmt->execute([$id, $amount, $currency, $userId])) {
        echo 'vc_success';
    }
} catch (PDOException $e) {
    error($e->getMessage(), true);
}

The MySQL database table referenced by the previous PHP sample can be created using the following code:

CREATE TABLE `AdColony_Transactions` (
    `id` INT(10) UNSIGNED NOT NULL PRIMARY KEY,
    `amount` INT(11) NOT NULL,
    `name` ENUM('Coin1', 'Coin2') NOT NULL,
    `user_id` INT(11) NOT NULL,
    `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;

To prevent duplicate transactions, you must make a record of the id of every transaction received, and check each incoming transaction id against that record after verifying the parameters. If a transaction is a duplicate, there is no need to reward the user.

After checking for duplicate transactions, you should reward your user the specified amount of the specified type of currency.

Step 4 - Configuring Your Server's Responses

You must ensure your server's response is appropriate based on the result of the transaction:

  • vc_success
    • Transaction finished. Return this when the callback is received and user credited.
  • vc_decline or vc_noreward
    • Transaction finished. Return this when the uid is not valid or the security check is not passed.
  • Anything else
    • AdColony will periodically retry to contact your server with this transaction. This should only be used in the case of some error.

Note: The only acceptable reasons to not reward a transaction are if the uid was invalid, the security check did not pass, or the transaction was a duplicate which was already rewarded.