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

Document created by Shrawan.Gupta on Feb 20, 2018Last modified by Shrawan.Gupta on Mar 16, 2018
Version 35Show Document
  • View in full screen mode

(Version 2.0.0)

Note: Sample code attached below (


OpenWrap - InApp enables publishers to 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. The OpenWrap call is made 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 an auction between bids from different header bidding partners configured by the publisher and selects a winning bid.
  4. This winning bid data (including bid eCPM, 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.


The OpenWrap In-App provides the following benefits:

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

Supported Ad Format

This depends on the supportedAPIs 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.



Integration of MoPub SDK & MoPub banner ad view


In-App Code Integration


Integrating the PubMatic Code in the Publisher’s Application

The publisher should refer to PubMatic's Sample Application for a faster, easier integration. The highlighted 'core' package needs to be copied to Publisher's Android application.


Updated screenshot of the 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 on making ad server (MoPub) request by passing prefetched 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>);


  • 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, please refer Table 4 in API Parameter details section.

  1. 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. 
    rofileId> = 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.

  2. Optionally, specify targeting information on the prefetch request object such as store URL, app domain, gender and much more.
    Sample code for setting basic parameters:

    // Designated market area (DMA) code of the user.

    // UDID specific params

    For additional parameter details, please refer Table 3 in the API Parameter details section.


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 () {
                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

                public void onBidsFailed(String errorMessage) {
                    // Failed to fetch bids from PubMatic.
                    // Request Mopub for ads without PubMatic bids
  3. Optionally, 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 It can be customized as per requirement. It defines the maximum timeout required to get the response from PubMatic ad server. Mopub call will be sent either PubMatic responds before this timeout or on elapsing this timeout.
  4. Call prefetchCreatives() on instance of PMPrefetchManager created in step 1.

Handling Prefetched Bids from PMPrefetchManager

  1. Upon Success, the Prefetch Manager will respond 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.
  2. Get an instance of MoPubView class (in MoPub SDK) 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 & 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(",");
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.

In the current sample code, bid price has been rounded up to 1 decimal place and can be customized as required. Make sure the similar line item has been configured in MoPub portal. Please refer to the Ad Server Setup section below.


Calling MoPub Ad with Pre-Fetched Bid Information

  1. Call loadAd() from MoPubView class object.
Disable the AutoRefresh feature on MoPubView using setAutorefreshEnabled() and use setRefreshInterval() on PMPrefetchManager object to refresh ads.

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

Publisher needs to implement a custom event adapter inheriting MoPub’s CustomEventBanner. For every winning bid, this adapter will receive callback where <serverExtras> contains the impressionId for which the wrapper bid has won. Assuming it has been configured in MoPub portal along with the full path of this adapter class.


protected void loadBanner(Context context, final CustomEventBannerListener
customEventBannerListener, Map<String, Object> localExtras, Map<String, String>
serverExtras) {

    String winningImpressionId = serverExtras.get("adunit");


Rendering Prfetched Creative

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

The attached code 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 that takes care of making calls to the ad server (MoPub). The PMWrapperManager handles fetching wrapper bids from PubMatic and handing over them to your wrapper object to initiate the ad server call.


The PMWrapperManager class can be used as a convenient way to integrate PubMatic's OpenWrap solution with an ad server; for example, MoPub.

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

You can write your own wrapper class implementing PMWrapper interface and handle ad server specific implementation. For example, PMMoPubWrapper in the following code.

Refer to attached code for more details. 

  1. Create a PMMopubWrapper object for each ad slot by providing slot name , list of ad sizes, and MoPubView.

    PMMopubWrapper wrapper = new PMMopubWrapper(<SlotName>, <AdSizes>, <MoPubView>);
  2. Write code that makes the ad server(MoPub) request in ‘requestAndLoadAd(<PMBid>)’ method. Note that the PMWrapperManager will call this method of your wrapper class, by passing the bid from PubMatic, to initiate the ad server call. Save this bid for rendering the ad later.
  3. Implement ‘impression()’ method to return the PMBannerImpression object. PMWrapperManager will use this method to get impression object representing your ad slot.
    Reference code to create a PMBannerImpression object -
    PMBannerImpression bannerImpression = new PMBannerImpression(<ImpressionId>, <SlotName>, 

    ImpressionId: Identifies 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: It is a string identifier. It should be the same slot name mapped to the wrapper ad tag. Refer to the PubMatic Mapping section.
    AdSizes: Array of PMAdSize objects for requesting an ad with different sizes.

  4. Create a list of PMMoPubWrapper objects, one wrapper object to represent a single 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 version id. (Refer to parameter details for information.)

    By default, the ‘live’ version of the profile will be used, if the version id is not set.
  6. Optionally set the targeting parameters in request object.

    // Create member variable: PMWrapperManager manager;
    manager = new PMWrapperManager(<PublisherId>, <ProfileId>, <WrapperArray>, <Context>);

    // Optional: Set version Id

    // Optional: Set targetting parameters to ad request for example

    // Optional: If refresh is needed

    <ProfileId> = Wrapper Profile Id of the publisher.

    <PublisherId> = Unique Publisher Id.

  7. Call loadAd() on wrapper manager.
    // Load ad


  8. The wrapper manager will fetch bids from PubMatic & will initiate ad server calls through your wrapper objects by passing these bids.

  9. Rendering the ad:
    Once the ad server notifies that the PubMatic bid has won, e.g. by using MoPub custom event, use the ‘getCreative()’ of PMBid from the bid stored in step 2 above & render the creative with your own implementation.
    This solution also provides a simple banner rendering. Just call PMWrapperManager.getPubMaticAdView(<Context>, <WinningImpressionId>) & pass the impression id for your ad slot. This will return you an object of customized WebView with rendered banner ad. Pass this to your MoPub's 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, i.e., by default auto-refresh feature is disabled. The publisher can set an appropriate refresh interval by calling setRefreshInterval(<value in sec>) of PMPrefetchManager. Expected value should be in range of 12 to 120.


Table 2. Ad Refresh Behavior on Setting Refresh Interval Value

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


Note: To use this feature, please disable the ad server’s refresh functionality. Please refer to the MoPub portal documentation for additional information.       


App debugging

OpenWrap code logs the request & response from the PubMatic server in debug mode. This debug log can help to see if PubMatic is providing proper bids or not. Below is a sample log from the OpenWrap sample application.

Updated production screenshot.


PubMatic Prefetch API Parameter Details

Please refer the following setter functions for sending the targeting parameter values.


Table 3. PMPrefetchRequest APIs/Setters

S. noMethodDescription
1setStoreURL(String storeUrl)URL of the app store from where a user can download this application. This URL must match the storeurl that is whitelisted in the UI.
2setAppDomain(String appDomain)Indicates the domain of the mobile application
3setApplicationPaid(boolean paid)

Indicates whether the mobile application is a paid version or not. 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:
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 such visitors should not be served targeted ads.


Possible options are:
false - Indicates that the visitor is not COPPA-specific and can be served targeted ads.
true - Indicates that 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

9setIABCategory(String iabCategory)

List of IAB content categories for the overall site/application. Refer the "Table 6.1 Content Categories" in the Open RTB 2.1 / 2.2 specifications document.

If the site/application falls under multiple IAB categories, you can send categories separated by comma

10setKeywords(String keyword)Sets the keywords list in the form of comma separated String. e.g. Cricket,Pizza 
11setLocation(Location location)Location object
12setAndroidAidEnabled(boolean isAndroidAidEnabled)

If set, it uses advertisement id otherwise it uses android id for targeting.

13setUdidHash(HASHING_TECHNIQUE hash)

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

14setVersionId(String id)

This is an optional Wrapper version Id of the publisher. If this is not specified, live version of the above profile is considered.

15setAppId(String id)

Exchange specific App Id

16setState(String state)

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

17setSummaryDisabled(boolean state)Set to true if summary in response should be disabled. By default it is set to false and hence summary would be fetched in the PMBid


Table 4. PMBannerImpression APIs/Setters



1setAdSizes(List<PMAdSize> adSizes)Sets the valid ad sizes
2setInterstitial(boolean interstitial)Set true if requesting for Interstitial ad. By default it is set to false.
3addCustomParam(String key, String value)Adds custom key-value parameters in Ad request. This method can be called multiple times with
same key and different values.
It will be internally sent as key1=val11,val12...|key2=val21,val22...
4setPMZoneId(String pmZoneId)Set the zone id. This parameter is used to pass a zone ID for reporting.
5setAdVisibility(AD_VISIBILITY adVisibility)Sets the fold placement of the ad to be served. Possible values are:
6setSupportedAPIs(API... apis)List of supported API frameworks for this impression. If an API is not explicitly listed, it is assumed not to be supported.
Possible values - VPAID1, VPAID2, MRAID1, ORMMA, MRAID2

Table 5. PMBid APIs

S. No.MethodDescription
1getTargetingInfo()Returns targeting information, that needs to be sent to ad server
2getTargetingInfoWithPricePrecision()Returns targeting information, that needs to be sent to ad server with specified price precision
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 if the bid wins
9getWidth()Returns Width of bid creative
10getHeight()Returns Height of bid creative

PubMatic Mapping 

Inventory mapping for PubMatic slots and ad tags must be completed in the PubMatic Admin console. Please contact your Customer Success Manager to complete this process.


Ad Server Setup on MoPub

The following steps are required so impressions can be allocated to PubMatic by the ad server, based on actual bid price and the recommendation from PubMatic. These are passed to the ad server using key-value pairs added to the MoPub ad request using PubMatic OpenWrap - InApp code.


The publisher needs to provide trafficker level access to create these line items to the email id provided by the PubMatic operations team.


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


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

  • Select Network for Type and a Priority of 12. (To enable PubMatic’s response to compete with MoPub Marketplace and Ad Networks).
  • Select Custom Native Network for the Network and add Class name and Data. <Class> is an adapter (subclass of CustomEventBanner class) class name. Data should be 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: Set targeting on the "pwtbst" value as 1 from the Openwrap response. In addition to the "pwtbst", you will need to set targeting on"pwtecp" which would be a winning bid from OpenWrap. You can set targeting on"pwtdid" (depending on custom key-value targeting). For more information please refer to the Best Practicesfor Creating Line Items in the Ad Server section. 


Pre-Launch Verification

Before setting traffic live, PubMatic’s Solutions Engineering team will assist the publisher’s technical and ad operations teams conduct 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 may:

  • Create multiple line items in the ad server for each ad unit/ad size/CPM range/geo.
  • Use “m_bid” as the targeting attribute.
  • 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 approximately add 300+ bid values in each line item, assuming each targeting line has 30 characters.

    This line item will match any ad request containing keyword "bidstatus:1,m_bid:0.#" (# between 0 to n) 
    m_bid:0.1 AND bidstatus:1
    m_bid:0.2 AND bidstatus:1
    m_bid:0.3 AND bidstatus:1
    m_bid:0.n AND bidstatus:1



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



Reporting is provided through PubMatic’s comprehensive analytics platform. Performance report provides insights into how PubMatic OpenWrap is performing.


  • MoPub reporting functionality should be used if reporting at the line item level is required.
  • Performance Report is available in the PubMatic UI. Select Analytics | Reports | Advanced Reports from the main navigation.


Sample Report