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

Document created by Shrawan.Gupta on Feb 16, 2018Last modified by Shrawan.Gupta on Mar 16, 2018
Version 29Show 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, DFP) to manage their ads. However, DFP 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 DFP SDK & DFP 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 the ad server (DFP) request by passing a 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 DFP ad with pre-fetched bid information
  5. Receiving a DFP App Event Callback
  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 DFP 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. 
    <ProfileId> = Wrapper Profile Id of the publisher.
    <Impressions> = List of PMBannerImpression objects created in step 1.

    Please contact your Customer Success Manager to get the 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 to Table 3 in API Parameter details section below.

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 DFP 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. DFP 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. Create a PublisherAdRequest.Builder object (in DFP SDK) providing it with all the custom targeting information using addCustomTargeting().
    PublisherAdRequest.Builder requestBuilder = new PublisherAdRequest.Builder();

    //Code to fetch the winning bid details for the impressionId & send to DFP
    PMBid bid = bidMap.get(<impressionId>);
    if (null != bid) {

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

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

            // using for-each loop for iteration over Map.entrySet()
            // send the targetting details to DFP ad server
            for (Map.Entry<String, String> entry : targeting.entrySet()) {
                requestBuilder.addCustomTargeting(entry.getKey(), entry.getValue());


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.

Calling DFP Ad with Pre-Fetched Bid Information

1. Create a PublisherAdRequest object, providing it with all the targeting information using requestBuilder:

PublisherAdRequest adRequest =;

2. Call loadAd() from PublisherAdView class object & pass the publisherAdRequest created in above step.


Receiving DFP App Event Callback

For every winning bid, a DFP app event callback is received via AppEventListener (from DFP SDK). 

  // Include string variables in class
  private final String PUBMATIC_WIN_KEY = "pubmaticdm";

Implement the AppEventListener and override the onAppEvent() callback method.

    private AppEventListener appEventListener = new AppEventListener() {
        public void onAppEvent(String key, String winningImpressionId) {
            //Check if event is for PubMatic then Render the Prefetched creative
            if (TextUtils.equals(key, PUBMATIC_WIN_KEY)) {
                // Write your rendering logic


    • key = app event name. It should be same as mentioned in Step 4 of section "Manual Creation of Ad Server Line Items"
    • winningImpressionId impressionId for which the wrapper bid has won.      

For getting the onAppEvent() callback method, make sure you assigned the app event listener to DFP ad view.


Rendering Prefetched 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 (DFP). 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, DFP.

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

You can write your own wrapper class implementing PMWrapper interface and implementing AppEventListener ( to handle DFP ad event). For example, PMDFPWrapper in the following code.

Refer to attached code for more details. 

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

    PMDFPWrapper wrapper = new PMDFPWrapper(<SlotName>, <AdSizes>, <DFPAdView>);
  2. Write code that makes the ad server(DFP) 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 DFP on screen.
    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 PMDFPWrapper 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 more 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 sending the PubMatic specific app event in PMDFPWrapper implemented above, use the ‘getCreative()’ from the bid stored in step 2 & render the creative with your own implementation.
    This solution also provides a simple banner rendering. Just call PMWrapperManager.getPubMaticAdView(<Context>, <PMBid>) & pass the bid stored in step2. This will return you an object of customized WebView with rendered banner ad. Add this into your parent view where you want to show the ad.


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 using the 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 <= 12Ad will get refreshed after every 12 seconds.
X > 12 & X <=120Ad will get refreshed after every X seconds
X > 120Ad will get refreshed after every 120 seconds

Note: To use this feature, please disable third party (e.g., DFP) refresh functionality. 

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.


Image of debug logs


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

Slot to tag Mapping

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

SeeOpenWrap User Guide for more details.


Ad Server Setup (DFP)

In addition to in-app code integration,  OpenWrap also requires at set of DFP ad server line items with small price increments. The PubMatic Operations team creates these line items using an internal tool. 


The publisher must provide trafficker level access to create these line items to the email id provided by the PubMatic operations team. The publisher decides the price granularity for the line items and informs the PubMatic operations team. The PubMatic Operations team will provide an Excel file containing the specification details upon request.


Manual Creation of Ad Server Line Items

For publishers who prefer to create their own ad server line items, this section explains how to set up the line items. OpenWrap passes bids to the ad server using key-value pairs added to the ad server tags dynamically, as explained in the sections above.

Note: The preferred option for the PubMatic TAM team is to support the order creation in DFP. The client just needs to provide trafficker-level access. Use PubMatic's order insertion tool to insert relevant orders into DFP and create granular line items. 


Step 1: Create a new order in DFP for a 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.

Step 3: Set targeting on the pwtbst value as 1. DFP uses this for reporting purposes. Also set targeting on pwtecp which would be a winning bid from OpenWrap. You can set targeting on pwtdid (depending on custom key-value targeting in DFP). For more information, see Best Practices to Create Tags in the Ad Server. 


Step 4: Add the OpenWrap In-App API creative provided by PubMatic to the line item you created.

<script type="text/javascript" src=""></script>
<script type="text/javascript">"pubmaticdm","%%PATTERN:bidid%%");

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 app is ready to go live. 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 “pwtecp” as the targeting attribute.
  • Use pwtbst as a targeting attribute. The value for this key must be 1 for all OpenWrap line items. This is used for reporting all wrapper line items in DFP and this key value is set in the Ad Server request by default by the SDK.
  • Place the line items at different priorities based on their pricing and relevance.

While creating line items at multiple price points, we recommend you create line items with more granular pricing where the bid density is high.


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: pwtecp=0.01*,pwtecp=0.02*....,pwtecp=0.09*, rate=$0.05
  • LineItem 2 (covers $0.10-$0.19) Targeting: pwtecp=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: pwtecp=3.0*,pwtecp=3.1*,pwtecp=3.2*, rate=$3.15
  • LineItem 32 (covers $3.30-$3.59) Targeting: pwtecp=3.3*,pwtecp=3.4*,pwtecp=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: pwtecp=9.*, rate=$9.5
  • LineItem 47 (covers $10.0-$10.99) Targeting: pwtecp=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: pwtecp=20*,pwtecp=21*,pwtecp=22*...... pwtecp=50*) rate= $21