Guide
Revenue and purchases
Optional. Most of this needs no code. Add the calls below for ad revenue from networks the SDK cannot see, StoreKit 2 purchases, your own user id, and NGA's own impressions.
Ad revenue from your mediation #
MAX and LevelPlay: nothing to do. When your game ships AppLovin MAX or Unity LevelPlay, the SDK records the revenue of each of their impressions from initialize on, even one that happens during a slow first launch. This covers the mediation your game runs on. A MAX or LevelPlay SDK that is in your build only as another mediation's adapter (AppLovin's or ironSource's inside AdMob, say) serves no impressions of its own and the SDK hears nothing from it; that revenue arrives through the mediation that served the ad.
AdMob and every other network: logAdRevenue. AdMob reports revenue only to each ad object, so the SDK cannot see it. Pass every paid event to logAdRevenue, impressions served by AdMob's AppLovin, ironSource or other adapters included: the SDK's MAX and LevelPlay hooks do not see AdMob's impressions, so nothing is counted twice:
Unity (C#)
using GoogleMobileAds.Api;
using NGA;
public static class AdMobRevenue
{
// Call once for each AdMob ad you load: AdMobRevenue.Track(interstitialAd, NGAAdFormat.Interstitial)
public static void Track(InterstitialAd ad, NGAAdFormat format)
{
ad.OnAdPaid += value => Log(value, ad.GetAdUnitID(), ad.GetResponseInfo(), format);
}
public static void Track(RewardedAd ad, NGAAdFormat format)
{
ad.OnAdPaid += value => Log(value, ad.GetAdUnitID(), ad.GetResponseInfo(), format);
}
static void Log(AdValue value, string adUnitId, ResponseInfo info, NGAAdFormat format)
{
var revenue = new NGAAdRevenue.Builder(NGAAdRevenueMediation.AdMob, value.Value, value.CurrencyCode, Precision(value.Precision))
.AdUnitId(adUnitId)
.AdFormat(format);
var source = info?.GetLoadedAdapterResponseInfo()?.AdSourceName;
if (source != null) revenue.Network(source);
NGASDK.LogAdRevenue(revenue.Build()); // AdValue.Value is already in micros
}
static NGARevenuePrecision Precision(AdValue.PrecisionType precision)
{
switch (precision)
{
case AdValue.PrecisionType.Precise: return NGARevenuePrecision.Exact;
case AdValue.PrecisionType.Estimated: return NGARevenuePrecision.Estimated;
case AdValue.PrecisionType.PublisherProvided: return NGARevenuePrecision.PublisherDefined;
default: return NGARevenuePrecision.Undefined;
}
}
}
Android (Kotlin)
import com.google.android.gms.ads.AdValue
import com.google.android.gms.ads.interstitial.InterstitialAd
import network.nga.sdk.NGAAdFormat
import network.nga.sdk.NGAAdRevenue
import network.nga.sdk.NGAAdRevenueMediation
import network.nga.sdk.NGARevenuePrecision
import network.nga.sdk.NGASDK
object AdMobRevenue {
// Call once for each AdMob interstitial you load; rewarded and other formats work the same way.
fun track(ad: InterstitialAd) {
ad.setOnPaidEventListener { value ->
val revenue = NGAAdRevenue.Builder(
NGAAdRevenueMediation.ADMOB,
value.valueMicros, // already in micros
value.currencyCode,
precision(value.precisionType),
)
.adUnitId(ad.adUnitId)
.adFormat(NGAAdFormat.INTERSTITIAL)
ad.responseInfo.loadedAdapterResponseInfo?.adSourceName?.let { revenue.network(it) }
NGASDK.logAdRevenue(revenue.build())
}
}
private fun precision(type: Int): NGARevenuePrecision = when (type) {
AdValue.PrecisionType.PRECISE -> NGARevenuePrecision.EXACT
AdValue.PrecisionType.ESTIMATED -> NGARevenuePrecision.ESTIMATED
AdValue.PrecisionType.PUBLISHER_PROVIDED -> NGARevenuePrecision.PUBLISHER_DEFINED
else -> NGARevenuePrecision.UNDEFINED
}
}
iOS (Swift)
import Foundation
import GoogleMobileAds
import NGASDK
enum AdMobRevenue {
// Call from the ad's FullScreenContentDelegate, which Google Mobile Ads 13.12 calls for each paid event:
// func ad(_ ad: FullScreenPresentingAd, didRecordPaidEventWith value: AdValue) { AdMobRevenue.log(value, for: ad) }
static func log(_ value: AdValue, for ad: FullScreenPresentingAd) {
// AdMob's iOS value is in currency units: convert once, by rounding, to micros.
let micros = value.value.multiplying(byPowerOf10: 6)
.rounding(accordingToBehavior: NSDecimalNumberHandler(roundingMode: .plain, scale: 0,
raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false))
.int64Value
let revenue = NGAAdRevenue.Builder(mediation: .admob, revenueMicros: micros,
currency: value.currencyCode, precision: precision(value.precision))
if let ad = ad as? InterstitialAd {
revenue.adFormat(.interstitial).adUnitId(ad.adUnitID)
if let source = ad.responseInfo.loadedAdNetworkResponseInfo?.adSourceName { revenue.network(source) }
} else if let ad = ad as? RewardedAd {
revenue.adFormat(.rewarded).adUnitId(ad.adUnitID)
if let source = ad.responseInfo.loadedAdNetworkResponseInfo?.adSourceName { revenue.network(source) }
}
NGASDK.logAdRevenue(revenue.build())
}
private static func precision(_ precision: AdValuePrecision) -> NGARevenuePrecision {
switch precision {
case .precise: return .exact
case .estimated: return .estimated
case .publisherProvided: return .publisherDefined
default: return .undefined
}
}
}
mediation is the layer that served the ad: ADMOB, MAX, LEVELPLAY or OTHER. An app with one network and no mediation uses NONE and sets network. Every field, with its rules and the errors a bad value gets, is on NGAAdRevenue. logAdRevenue returns an NGAResult immediately.
Logging an ad the SDK already records (a MAX or LevelPlay impression) does no harm as long as the call carries that mediation's own impression id (MAX's ad id, LevelPlay's auction id) or none: NGA keeps one copy. With an id of your own, both copies are kept.
Purchases #
Most games need no code: Google Play Billing 8 or later, StoreKit 1, and Unity IAP 4. From initialize on, the SDK sees these purchases without changing your purchase flow. It never acknowledges, consumes or finishes a purchase. A StoreKit 1 restore is not recorded as a new purchase, with one exception: after a reinstall, a restored subscription's latest period can be recorded once if the SDK had not seen it before; NGA counts each transaction once across installs.
iOS games on StoreKit 2: one call per purchase. A StoreKit 2 consumable that you finish immediately reaches only your own code, so pass every successful Product.purchase() result to logPurchase. A purchase the SDK also sees on its own is still recorded once.
iOS (Swift)
import StoreKit
import NGASDK
enum Store {
static func buy(_ product: Product) async throws {
let result = try await product.purchase()
guard case .success(let verification) = result else { return }
NGASDK.logPurchase(verification) // every successful purchase, consumable or not
if case .verified(let transaction) = verification {
// Deliver the item, then:
await transaction.finish()
}
}
}
Unity IAP 5: one call per purchase. On iOS, Unity IAP 5 uses StoreKit 2. Pass the order's JWS to LogPurchase just before ConfirmPurchase. On Android the call records nothing and returns accepted, so the same script works on both platforms.
Unity (C#)
using NGA;
using UnityEngine.Purchasing;
public class Purchases
{
readonly StoreController store = UnityIAPServices.StoreController();
public Purchases() { store.OnPurchasePending += OnPurchasePending; }
void OnPurchasePending(PendingOrder order)
{
// Deliver the item, then:
NGASDK.LogPurchase(order.Info.Apple?.jwsRepresentation); // iOS: the StoreKit 2 transaction; Android: ignored
store.ConfirmPurchase(order);
}
}
What the SDK does not see: other stores (Amazon, Samsung, Huawei, web shops), Play Billing below version 8, purchases granted only on your server, and purchases made before the SDK first ran. Google Play refunds are not visible on the device.
Your own user id #
setCustomerUserId attaches your own id for the player, such as your account id, so NGA's data can be joined with yours. NGA stores it hashed.
Unity (C#)
using NGA;
using UnityEngine;
public static class PlayerAccount
{
public static void OnSignedIn(string accountId)
{
var result = NGASDK.SetCustomerUserId(accountId);
if (!result.Accepted) Debug.LogWarning($"NGA customer user id: {result.Error.Detail}");
}
public static void OnSignedOut() { NGASDK.SetCustomerUserId(null); }
}
Android (Kotlin)
import android.util.Log
import network.nga.sdk.NGASDK
object PlayerAccount {
fun onSignedIn(accountId: String) {
val result = NGASDK.setCustomerUserId(accountId)
if (!result.accepted) Log.w("Game", "NGA customer user id: ${result.error?.detail}")
}
fun onSignedOut() {
NGASDK.setCustomerUserId(null)
}
}
iOS (Swift)
import NGASDK
enum PlayerAccount {
static func onSignedIn(accountId: String) {
let result = NGASDK.setCustomerUserId(accountId)
if !result.accepted { print("NGA customer user id: \(result.error?.detail ?? "")") }
}
static func onSignedOut() {
NGASDK.setCustomerUserId(nil)
}
}
null removes the id, for example at sign-out. Without analytics consent, or under child treatment, NGA receives only the fact that an id is set, never the id. The id's format and errors: setCustomerUserId.
NGA's own impressions #
One app-wide listener reports every NGA impression with its exact payout, for your own analytics. NGA already records these impressions; do not pass them to logAdRevenue.
Unity (C#)
using NGA;
using UnityEngine;
public static class NGAImpressions
{
// Once, after Initialize. A later call replaces the listener; null removes it.
public static void Listen()
{
NGASDK.SetImpressionListener(imp =>
Debug.Log($"NGA impression {imp.OpportunityId}: {imp.RevenueMicros} micros {imp.Currency}, " +
$"{imp.Format}, promoting {imp.AdvertiserBundle}"));
}
}
Android (Kotlin)
import android.util.Log
import network.nga.sdk.NGASDK
object NGAImpressions {
// Once, after initialize. A later call replaces the listener; null removes it.
fun listen() {
NGASDK.setImpressionListener { imp ->
Log.i(
"Game",
"NGA impression ${imp.opportunityId}: ${imp.revenueMicros} micros ${imp.currency}, " +
"${imp.format}, promoting ${imp.advertiserBundle}",
)
}
}
}
iOS (Swift)
import NGASDK
enum NGAImpressions {
// Once, after initialize. A later assignment replaces the listener; nil removes it.
static func listen() {
NGASDK.impressionListener = { imp in
print("NGA impression \(imp.opportunityId): \(imp.revenueMicros) micros \(imp.currency), "
+ "\(imp.format.rawValue), promoting \(imp.advertiserBundle ?? "-")")
}
}
}
In 0.1.0 every NGA impression promotes one of your own games, so: revenueMicros is 0; precision is EXACT; advertiserBundle is the promoted game's store id; creativeId is null for the native banner. The fields are on NGAImpression.