OpenWrap In-App v2.0.2 Developer Guide for MoPub (Android)

Document created by Shrawan.Gupta on Feb 20, 2018Last modified by david.simerly on Jun 11, 2018
Version 48Show Document
  • View in full screen mode
Download the OpenWrap for Android sample app—OpenWrap_Android.zip

Introduction

OpenWrap-InApp lets publishers solicit multiple programmatic bids for their mobile in-app inventory. OpenWrap sends an initial ad call to one or more header bidding partners to solicit bids for inclusion in the ad server’s inventory allocation process.

 

High-Level Process Overview

  1. OpenWrap makes the call before requesting an ad from the primary AdServer SDK.
  2. Programmatic buyers get first look at the inventory and submit a bid price.
  3. OpenWrap conducts a server-side auction between bids from different header bidding partners configured by the publisher, then selects a winning bid.
  4. The winning bid data (including bid eCPM and winning partner) is included in the ad server call, which checks if any other buyers in the same priority tier can beat it. As a result, inventory gets allocated to the highest yielding buyer while respecting other publisher controls that may have been set up in the ad server.

 

OpenWrap primarily benefits publishers who use third party SDKs (for example, MoPub) to manage their ads. However, MoPub doesn’t allow publishers to effectively pull in programmatic buyers that compete against AdX and direct deals, so publishers are limited in the buyers they can use.

 

When a view with an ad slot in the publisher's app loads, the OpenWrap code sends a request to the OpenWrap S2S service for bids before calling the ad server. OpenWrap makes the bid requests in parallel instead of using a sequential waterfall and provides publishers with access to many sources of demand.

 

The diagram below shows how PubMatic OpenWrap integrates with a publisher’s app.

 

 

If desired, publishers can also allow the winning bid to compete with prices available from the direct-sold ads.

 

OpenWrap In-App provides the following benefits:

  • All demand sources are bidding at the same time, which replaces waterfall’s preferential ordering of buyers.
  • Advertisers have a chance to obtain the best ad inventory.
  • Publishers have seen a monetization increase as much as 50%.

Supported Ad Format

Determined by the setSupportedAPIs parameter value you set on a PMBannerImpression object. This solution gives you full rendering control and applications use their own rendering capabilities to support specific API frameworks such as, MRAID1, MRAID2, VPAID, ORMMA, and so on.

 

Prerequisites

 

In-App Code Integration

Download the OpenWrap for Android sample app for faster, easier integration. Copy the highlighted core package into your Android app project.

 

 

Adding Permissions to the Manifest File

Declare the following security permissions in your manifest file (AndroidManifest.xml).

 

Table 1: Basic Permissions for the Manifest File

PermissionDescription and Manifest File Entry
InternetAccess the Internet. Required for ad-content download.
<uses-permission android:name="android.permission.INTERNET" />
Network StateAccess the Network state. Required for retrieving network details from ConnectivityManager.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 

This solution provides two integration approaches. Use the approach that satisfies your requirements.

 

 

Approach 1: Prefetch Bids using PMPPrefetchManager & PMPrefetchRequest

Use the APIs to simply prefetch bids using PMPrefetchManager and PMPrefetchRequest. You get full control of the ad server (MoPub) request by passing prefetch bid and handling ad server mechanism to determine if the bid wins.

 

  1. Creating a Prefetch Request
  2. Prefetching Bids Using PMPrefetchManager
  3. Handling Prefetched Bids from PMPrefetchManager
  4. Calling Mopub Ad With Pre-Fetched Bid Information
  5. Receiving Winning Bids Using MoPub's Custom Event (Adapter) Class
  6. Rendering Prefetched Creative

 

Creating a Prefetch Request

  1. Create Impression objects that contain information about specific ad slots like impressionId (Unique identifier), slot name and sizes. It is required to make an ad request to PubMatic against impression objects. You may optionally set pmZoneId, custom parameters and supported API framework for this impression. For example:
    PMBannerImpression bannerImpression = new PMBannerImpression(<ImpressionId>, <SlotName>, <AdSizes>);
    bannerImpression.setPMZoneId("123");
    bannerImpression.setAdVisibility(PMBannerImpression.AD_VISIBILITY.ABOVE_THE_FOLD);

    <ImpressionId>: used to identify unique ad slot/banner of Mopub on screen, this should match with imp_id configured at step 2 in Ad Server Setup section below.

    <SlotName>: a string identifier. It should be the same slot name mapped to PubMatic ad tag. Refer to the inventory mapping completed by PubMatic.

    <AdSizes>: list of PMAdSize to be provided to request an ad with different sizes.

    For additional parameter details, see Table 4 in PubMatic Prefetch API Parameter Details.
  2. Create a prefetch request object by specifying the publisher id and impressions, from step 1, to prefetch bids. It is required to make an ad request to PubMatic against impression objects.
    PMPrefetchRequest adRequest = PMPrefetchRequest.createInstance(<Context>, <PublisherId>, <ProfileId>, <Impressions>);

    <PublisherId> = unique publisher id.
    <ProfileId> = wrapper Profile Id of the publisher.
    <Impressions> = list of PMBannerImpression objects created in step 1.

    Please contact your Customer Success Manager to get PublisherId and ProfileId.
  3. Optionally, specify targeting information on the prefetch request object such as store URL, app domain, gender and much more. Your code may resemble the following:
    adRequest.setKeywords("entertainment,sports");
    adRequest.setApplicationPaid(false);
    adRequest.setCoppa(true);
    adRequest.setIABCategory("IAB1-1,IAB1-7");
    adRequest.setGender(PMPrefetchRequest.GENDER.MALE);

    // Designated market area (DMA) code of the user.
    adRequest.setDMA("734");

    // UDID specific params
    adRequest.setAndroidAidEnabled(true);
    adRequest.setUdidHash(PMPrefetchRequest.HASHING_TECHNIQUE.RAW);
    For additional parameter details, see Table 3 in PubMatic Prefetch API Parameter Details.

 

Prefetching Bids Using PMPrefetchManager

  1. Create a Prefetch Manager object.
    PMPrefetchManager pmPrefetchManager = new PMPrefetchManager();
  2. Create an object of PMPrefetchListener and set it to PMPrefetchManager, created in above step:
    PMPrefetchManager.PMPrefetchListener listener = new PMPrefetchManager.PMPrefetchListener () {
                @Override
                public void onBidsFetched(Map<String, PMBid> bidMap) {
                   
                    // Pre-fetching of bids completed from PubMatic.
                    // Now handels fetched Bids from PMPrefetchManager
                    // Refer next section for more details
                }

                @Override
                public void onBidsFailed(String errorMessage) {
                   
                    // Failed to fetch bids from PubMatic.
                    // Request Mopub for ads without PubMatic bids
                }
            };
    pmPrefetchManager.setPrefetchListener(listener);
  3. Set a network timeout using setNetworkTimeout(<timeout in seconds>) method on PMPrefetchManager instance. Default network timeout is 3 seconds, defined as NETWORK_TIMEOUT_SECONDS in PubMaticConstants.java. You can customize it as required. It defines the maximum timeout to wait for the response from PubMatic ad server. Mopub call is sent if PubMatic responds before the timeout, or when the timeout elapses.
    pmPrefetchManager.setNetworkTimeout(<TIMEOUT>);
  4. Call prefetchCreatives() on instance of PMPrefetchManager created in step 1.
    pmPrefetchManager.prefetchCreatives(<PMBannerPrefetchRequest>);

 

Handling Prefetched Bids from PMPrefetchManager

Upon Success, the Prefetch Manager responds with a callback onBidsFetched() with a map of PMBid objects.

 

The keys for this map will be the impression ids. The PMBid object will contain impression ids and bid information. Save these bids and use them for rendering ads, later if the wrapper bid wins.

 

Get an instance of MoPubView class (in MoPub SDK) by providing it with all the targeting information using setKeywords():

//Include string variables in class 
private final int BID_DECIMAL_ROUNDOFF= 1;

//Fetch the winning bid details for the impressionId and send to MoPub
PMBid bid = bidMap.get(<impressionId>);
if (null != bid) {

    StringBuilder keywords = new StringBuilder();

    Map<String, String> targeting = bid.getTargetingInfoWithPricePrecision(BID_DECIMAL_ROUNDOFF);

    if (targeting != null && targeting.isEmpty() == false) {

        // using for-each loop for iteration over Map.entrySet()
        for (Map.Entry<String, String> entry : targeting.entrySet()) {
            keywords.append(entry.getKey() + ":" + entry.getValue()).append(",");
        }
    }
    mAdView.setKeywords(keywords.toString());
}

 

Targeting map contains deal id (for key pwtdid), which  is used for PMP deals and bid status (for key pwtbst), which is used for reporting.

The OpenWrap for Android sample app rounds up to 1 decimal place, which you can customize as required. Make sure the similar line item has been configured in MoPub portal. See Ad Server Setup on MoPub for details.

 

Calling MoPub Ad With Pre-Fetched Bid Information

Call loadAd() from the MoPubView class object.

mopubView.loadAd();
Disable the auto-refresh feature on MoPubView using setAutorefreshEnabled() and use setRefreshInterval() on the PMPrefetchManager object to refresh ads.

 

Receiving Winning Bids Using MoPub's Custom Event (Adapter) Class

Next you must implement a custom event adapter inheriting MoPub’s CustomEventBanner. This adapter receives callbacks for every winning bid; <serverExtras> contains the impressionId for which the wrapper bid has won. You must also configure the MoPub portal with the full path for this adapter class.

 

@Override 
protected void loadBanner(Context context, final CustomEventBannerListener
customEventBannerListener, Map<String, Object> localExtras, Map<String, String>
serverExtras) {
    String winningImpressionId = serverExtras.get("adunit");
}

 

Rendering Prefetched Creative

Fetch the PMBid object, for the winning impression id from the bids you saved earlier in the onBidsFetched() callback of PMPrefetchListener. This object contains the winning creative in getCreative(). Use this method to render the ad. For example, use a simple WebView for a banner ad, or a custom MRAID or VPAID ad.

The OpenWrap for Android sample app demonstrates how to render a simple banner creative using a WebView.

Approach 2: Using PMWrapperManager

This solution provides a standard way (implementing PMWrapper interface), to easily write your wrapper class to handle making calls to the MoPub ad server. The PMWrapperManager handles fetching wrapper bids from PubMatic and handing over them to your wrapper object to initiate the ad server call.

 

Use the PMWrapperManager class as a convenient way to integrate PubMatic's OpenWrap solution with an ad server like MoPub.

PMWrapperManager initiates prefetch requests to PubMatic, and also to MoPub ad server through wrapper objects that implement the PMWrapper interface.

You can write your own wrapper class implementing PMWrapper interface and handle ad server specific implementation, similar to PMMoPubWrapper in the OpenWrap for Android sample app.

  1. Create a PMMopubWrapper object for each ad slot by providing slot name, list of ad sizes, and MoPub View.
    PMMopubWrapper wrapper = new PMMopubWrapper(<SlotName>, <AdSizes>, <MoPubView>);
  2. Add code to generate the MoPub ad server request in the requestAndLoadAd(<PMBid>) method. Note that the PMWrapperManager calls this method of your wrapper class by passing the bid from PubMatic to initiate the ad server call.
    Save this bid to render the ad later.
  3. Implement the impression() method to return the PMBannerImpression object. PMWrapperManager uses this method to get impression objects representing your ad slots. Your PMBannerImpression object should be similar to this:

    PMBannerImpression bannerImpression = new PMBannerImpression(<ImpressionId>, <SlotName>, 
    <AdSizes>);

    <ImpressionId> identifies unique MoPub ad slots/banners on screen, which should match with imp_id configured at step 2 in Ad Server Setup on MoPub.

    <SlotName> = a string identifier that should match the slot name mapped to the wrapper ad tag. See PubMatic Mapping.

    <AdSizes>: an array of PMAdSize objects for requesting an ad with different sizes.

  4. Create a list of PMMoPubWrapper objects, one wrapper object per ad slot.
  5. Create an object of PMWrapperManager with the wrapper object's list created in step 1 and a profile id. You can optionally set the version id; see PubMatic Prefetch API Parameter Details.
    If the version id is not set, OpenWrap defaults to the live version of the profile.
  6. Optionally, set the targeting parameters in the request object.
    // Create member variable: PMWrapperManager manager;
    manager = new PMWrapperManager(<PublisherId>, <ProfileId>, <WrapperArray>, <Context>);

    // Optional: Set version Id
    manager.prefetchRequest.setVersionId(<VersionId>);

    // Optional: Set targetting parameters to ad request for example
    manager.prefetchRequest.setDMA("734");
    manager.prefetchRequest.setAndroidAidEnabled(true);

    // Optional: If refresh is needed
    manager.setRefreshInterval(<RefreshInterval>);

    // Load ad
    manager.loadAd();

    <ProfileId> = wrapper profile Id of the publisher.

    <PublisherId> = unique publisher Id.

  7. Call loadAd() on wrapper manager.
    // Load ad
    manager.loadAd();
  8. The wrapper manager fetches bids from PubMatic and initiates ad server calls through your wrapper objects by passing those bids.

 

Rendering the Ad

Once the ad server notifies that a PubMatic bid has won (using a MoPub custom event, for example), use the getCreative() of PMBid from the bid stored in step 2 above to render the creative within your own implementation.

 

This solution also provides a simple banner rendering. Just call PMWrapperManager.getPubMaticAdView(<Context>, <WinningImpressionId>) and pass the impression id for your ad slot. This returns an object of customized WebView with a rendered banner ad. Pass this to your MoPub custom event listener. For example:

CustomEventBannerListener.onBannerLoaded(<WebView>);

 

Setting Refresh Interval (Optional)

This solution provides an optional feature to auto-refresh the banner ad after a specified interval.

The default value for refresh interval is 0 seconds; that is, by default auto-refresh feature is disabled. You can set your own refresh interval by calling setRefreshInterval(<value in sec>) of PMPrefetchManager. Expected value should be in the range of 12 to 120 seconds.

 

Table 2: Ad Refresh Behavior on Setting Refresh Interval Value

Value (X) in secondsBehavior
X <= 0Ad will not refresh
X > 0 and X <= 12Ad will get refreshed after every 12 seconds.
X > 12 and X <= 120Ad will get refreshed after every X seconds
X > 120Ad will get refreshed after every 120 seconds

 

To use this feature, first disable the ad server’s native refresh functionality. See the MoPub portal documentation for additional information.

 

App debugging

OpenWrap logs the request and response from the PubMatic server in debug mode. The debug log determine whether or not PubMatic is providing proper bids. Below is a sample log from the OpenWrap for Android sample application.

 

 

PubMatic Prefetch API Parameter Details

Use the following setter functions for sending ad targeting parameter values.

 

Table 3: PMPrefetchRequest APIs/Setters

S. No.MethodDescription
1setStoreURL(String storeUrl)URL of the app store where a user can download your app. This URL must match the storeurl that is whitelisted in the UI.
2setAppDomain(String appDomain)Indicates the domain of your mobile app.
3setApplicationPaid(boolean paid)Indicates whether your app is a free or paid version. Possible values are:
  • False = free version.
  • True = paid version.
4setBirthYear(String yearOfBirth)Visitor's birth year as a four-digit integer; for example, 1975.
5setGender(PMPrefetchRequest.GENDER gender)Gender of the visitor. Possible values are:
  1. MALE
  2. FEMALE
  3. OTHER
6setCity(String city)City of the user. For example, city=New York
7setZip(String zip)Home zip code if the visitor is present in the U.S.; otherwise it indicates the postal code.
8setCoppa(boolean coppa)Indicates whether the visitor is COPPA-specific or not. For COPPA (Children's Online Privacy Protection Act) compliance, if the visitor's age is below 13, then the visitor should receive targeted ads. Possible options are:
  1. False - the visitor is not COPPA-specific and can receive targeted ads.
  2. True - the visitor is COPPA-specific and should be served only COPPA-compliant ads.
The United States Federal Trade Commission has written a comprehensive FAQ on complying with COPPA at http://business.ftc.gov/documents/Complying-with-COPPA-Frequently-Asked-Questions.
9setIABCategory(String iabCategory)List of IAB content categories for the overall site/application. See "Table 6.1 Content Categories" in the Open RTB 2.2 Specifications. If the site/application falls under multiple IAB categories, you can send comma-delimited categories.
10setKeywords(String keyword)Sets the keywords list as a comma-delimited String. For example, Calzone,Pizza,Pasta,Salad.
11setLocation(Location location)Location object.
12setAndroidAidEnabled(boolean isAndroidAidEnabled)If set, it uses advertisement id, otherwise it uses the Android id for targeting.
13setUdidHash(HASHING_TECHNIQUE hash)

Based on the given hashing type, UDID value hashed and sent to the ad server.

14setVersionId(String id)

An optional wrapper version Id of the publisher. If this is not specified, OpenWrap uses the live version of the profile.

15setAppId(String id)

Exchange specific app Id.

16setState(String state)

Sets the region code using ISO-3166-2; a 2-letter state code if USA.

17setSummaryDisabled(boolean state)Set to True to disable the response summary. The default is False which returns a summary in the fetched PMBid.

 

Table 4: PMBannerImpression APIs/Setters

S. No.MethodDescription
1setAdSizes(List<PMAdSize> adSizes)Sets the valid ad sizes.
2setInterstitial(boolean interstitial)Set True if requesting an Interstitial ad. The default is false.
3addCustomParam(String key, String value)Adds custom key-value parameters to an Ad request. Call this method multiple times with the same key and different values to add multiple values to a single key; for example, key1=val11,val12...|key2=val21,val22....
4setPMZoneId(String pmZoneId)Sets the zone id used for reporting.
5setAdVisibility(AD_VISIBILITY adVisibility)Sets the fold placement of the ad to be served. Possible values are:
  • UNKNOWN
  • ABOVE_THE_FOLD
  • BELOW_THE_FOLD
  • HEADER
  • FOOTER
  • SIDEBAR
  • FULL_SCREEN
6setSupportedAPIs(API... apis)List of supported API frameworks for this impression. If an API is not explicitly listed, assume it is unsupported. Possible values:
  • VPAID1
  • VPAID2
  • MRAID1
  • ORMMA
  • MRAID2

 

Table 5: PMBid APIs

S. No.MethodDescription
1getTargetingInfo()Returns targeting information to send to the ad server.
2getTargetingInfoWithPricePrecision()Returns targeting information with specified price precision to send to the ad server.
3getImpressionId()Returns Impression Id. Also used as a bid id.
4getPrice()Returns Price/bid value.
5getCreative()Returns ad creative.
6getDealId()Returns deal Id. Used for PMP deals
7getSummary()Returns bid summary for debugging purpose.
8getnURL()Returns win-notice URL called by the exchange when a bid wins.
9getWidth()Returns the horizontal width of bid creative.
10getHeight()Returns the vertical height of bid creative.

 

PubMatic Mapping

Inventory mapping for demand sources/header bidding partners configured in OpenWrap must be completed in the PubMatic Wrapper UI. This process creates a wrapper profile where publishers map Ad Server slots to the partner specific ad units; for example, PubMatic ad tag, AppNexus placement ID, and so on.

See OpenWrap User Guide for details.

Ad Server Setup (MoPub)

The following steps enable MoPub ad server to allocate impressions to PubMatic based on actual bid price and PubMatic's recommendation. Data are passed to the ad server using key-value pairs added to the MoPub ad request using PubMatic OpenWrap In-App code.

Publishers must provide trafficker level acces (able to create line items), to the email id provided by the PubMatic operations team.

Step 1: Create a new order in MoPub for In-App Header Bidding API with PubMatic as the advertiser and add the relevant details.

 

Step 2: Set the price and priority of the line items.

  • For the Type & Priority drop-downs, choose Network for Type and 12 for Priority (to enable PubMatic’s response to compete with MoPub Marketplace and Ad Networks).
  • Next select Network > Custom Native Network.
  • In the Class field, enter the name of an adapter class (subclass of CustomEventBanner class).
  • In the Data field, enter a map of <imp_id>:<adunit_id>. Add <imp_id>; same as impression id passed in PMBannerImpression.

 

 

Step 3: Ad unit targeting. Assign line items to appropriate ad units.

 

Step 4: In the Keywords list, set targeting on the pwtbst value as 1 from the Openwrap response. In addition to the pwtbst, set targeting on pwtecp, which would be a winning bid from OpenWrap. You can also set targeting on pwtdid (depending on custom key-value targeting). For more information see Best Practices for Creating Line Items in the Ad Server.

 

 

Pre-Launch Verification

Before setting traffic live, PubMatic’s Solutions Engineering team will assist the publisher’s technical and ad operations teams to conduct a pre-launch verification. Once verifications are complete, the set-up is ready to go live on a small number of sites. Post-launch, the PubMatic Operations team will ensure that the publisher is achieving the desired results and will provide consultation to ramp-up the implementation.

 

Best Practices for Creating Line Items in the Ad Server

To control monetization through OpenWrap In-App at a granular level, you can:

 

  • Create multiple Openwrap line items in the ad server for each ad unit, ad size, CPM range, and geo.
  • Use pwtecp as the targeting attribute. This is the bid eCPM from the OpenWrap auction.
  • Use pwtbst as a targeting attribute; the value for this key must be 1 for all OpenWrap line items.
  • Place the line items at different priorities based on their pricing and relevance.
Important Notes:
  • Currently, PubMatic supports (one decimal point) 10-cent granularity in key-value targeting.
  • The maximum length of the keywords that MoPub supports is 10K characters. As a result, you can add approximately 300+ bid values in each line item, assuming each targeting line has 30 characters.
Example:
These line items match any ad request containing keyword "pwtbst:1, pwtecp:0.#" (# between 0 to n):

 

pwtecp:0.1 AND pwtbst:1
pwtecp:0.2 AND pwtbst:1
pwtecp:0.3 AND pwtbst:1
...
pwtecp:0.n AND pwtbst:1

 

Examples:

If 80% of the bids are between $0 to $3, create line items at a $0.1 granularity. For other ranges you can create line items at a higher granularity.

 

Sample Variations:
30 line items between $0-$3 with rate increment of $0.1

  • LineItem 1 (covers $0-$0.09) Targeting: bid=0.01,bid=0.02....,bid=0.09, rate=$0.05
  • LineItem 2 (covers $0.10-$0.19) Targeting: bid=0.1, rate=$0.15

       and so on for next 28 line items

15 Line items between $3-$8 with rate increment of $0.30

  • LineItem 31 (covers $3.0-$3.29) Targeting: bid=3.01,bid=3.1,bid=3.2, rate=$3.15
  • LineItem 32 (covers $3.30-$3.59) Targeting: bid=3.3,bid=3.4,bid=3.5, rate=$3.45

       and so on for next 13 line items

12 Line items between $9-$20 with rate increment of $1.0

  • LineItem 46 (covers $9.0-$9.99) Targeting: bid=9, rate=$9.5
  • LineItem 47 (covers $10.0-$10.99) Targeting: bid=10, rate=$3.45

       and so on for next 10 line items

A final high- priority line item for very high bids

  • Line Item 58 (Covers $20 and above) Targeting : bid=20,bid=21,bid=22...... bid=50) rate= $21

 

⇧ Top

Attachments

Outcomes