Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PubMatic 1.0 adapter #2011

Merged
merged 35 commits into from
Jan 23, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
00b4fb7
Merge remote-tracking branch 'refs/remotes/prebid/master'
pm-harshad-mane Oct 17, 2017
f076c44
Merge remote-tracking branch 'refs/remotes/prebid/master'
pm-harshad-mane Nov 22, 2017
ea97b7e
Merge remote-tracking branch 'refs/remotes/prebid/master' into PubMat…
pm-harshad-mane Dec 10, 2017
6237a0a
first commit
pm-harshad-mane Dec 11, 2017
d713a4e
ip field removed, added comments to params, netRevenue set to true
pm-harshad-mane Dec 11, 2017
10a8fa0
added _processFloor
pm-harshad-mane Dec 11, 2017
3a8cbe4
removed comments
pm-harshad-mane Dec 11, 2017
b6e7805
fixed unit test cases
pm-harshad-mane Dec 11, 2017
80c4d2f
Merge pull request #9 from pm-harshad-mane/PubMatic_One
PubMatic-OpenWrap Dec 12, 2017
24b8772
review comments
pm-harshad-mane Dec 12, 2017
143461c
added method _parseSlotParam
pm-harshad-mane Dec 12, 2017
97c3ea4
minor changes
pm-harshad-mane Dec 12, 2017
f93c0fb
minor change
pm-harshad-mane Dec 12, 2017
c8f7293
publisherId isStr check added
pm-harshad-mane Dec 12, 2017
ec96c34
test case for string publisherId and adSlot
pm-harshad-mane Dec 12, 2017
5c34e03
using prebid apis for getting pageURL and refURL,
pm-harshad-mane Dec 12, 2017
9f9b3ce
bid precision set to 2
pm-harshad-mane Dec 12, 2017
7c94786
Added test cases for interpretResponse function
pm-manasi-moghe Dec 13, 2017
90d4ba6
do not put warning for undefined valued params
pm-harshad-mane Dec 13, 2017
e4397d6
Merge branch 'PubMatic-1.0' of https://github.com/PubMatic-OpenWrap/P…
pm-manasi-moghe Dec 14, 2017
bd009e8
changes for UOE-3239 and UOE-3236
pm-manasi-moghe Dec 15, 2017
5aa0839
Linting errors fixed
pm-manasi-moghe Dec 15, 2017
3ed2033
Add geo object in device
pm-dattaprasad-mundada Dec 15, 2017
eda0b4b
Changes to trim kadpageurl and pmzoneid before sending it in request
pm-manasi-moghe Dec 20, 2017
f33459e
Remove spaces when multiple Id's added in pmzoneId
pm-dattaprasad-mundada Dec 20, 2017
f16e42c
rolling back changes for pmzoneid
pm-manasi-moghe Dec 21, 2017
7072d3c
Add PubMaticBidAdapter param info
pm-dattaprasad-mundada Dec 22, 2017
23151be
Update params in pubmaticBidAdapter.md
pm-dattaprasad-mundada Dec 22, 2017
6ed1a46
Update maintainer mail-id
pm-dattaprasad-mundada Jan 3, 2018
d81bf1c
endpoint changed to hbopenbid.pubmatic.com, netRevenue default value …
pm-manasi-moghe Jan 4, 2018
23d990d
changed auction type to 1
PubMatic-OpenWrap Jan 5, 2018
8f5652a
changed at to 1 in test cases
PubMatic-OpenWrap Jan 5, 2018
2ac7153
removed comments
PubMatic-OpenWrap Jan 11, 2018
b039912
UserSync requirements are mentioned in .md file
PubMatic-OpenWrap Jan 11, 2018
bd9ad84
updated test ids
PubMatic-OpenWrap Jan 11, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
291 changes: 291 additions & 0 deletions modules/pubmaticBidAdapter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,291 @@
import * as utils from 'src/utils';
import { registerBidder } from 'src/adapters/bidderFactory';
const constants = require('src/constants.json');

const BIDDER_CODE = 'pubmatic';
const ENDPOINT = '//hbopenbid.pubmatic.com/translator?source=prebid-client';
const USYNCURL = '//ads.pubmatic.com/AdServer/js/showad.js#PIX&kdntuid=1&p=';
const CURRENCY = 'USD';
const AUCTION_TYPE = 1;
const UNDEFINED = undefined;
const CUSTOM_PARAMS = {
'kadpageurl': '', // Custom page url
'gender': '', // User gender
'yob': '', // User year of birth
'lat': '', // User location - Latitude
'lon': '', // User Location - Longitude
'wiid': '', // OpenWrap Wrapper Impression ID
'profId': '', // OpenWrap Legacy: Profile ID
'verId': '' // OpenWrap Legacy: version ID
};
const NET_REVENUE = false;

let publisherId = 0;

function _getDomainFromURL(url) {
let anchor = document.createElement('a');
anchor.href = url;
return anchor.hostname;
}

function _parseSlotParam(paramName, paramValue) {
if (!utils.isStr(paramValue)) {
paramValue && utils.logWarn('PubMatic: Ignoring param key: ' + paramName + ', expects string-value, found ' + typeof paramValue);
return UNDEFINED;
}

switch (paramName) {
case 'pmzoneid':
return paramValue.split(',').slice(0, 50).map(id => id.trim()).join();
case 'kadfloor':
return parseFloat(paramValue) || UNDEFINED;
case 'lat':
return parseFloat(paramValue) || UNDEFINED;
case 'lon':
return parseFloat(paramValue) || UNDEFINED;
case 'yob':
return parseInt(paramValue) || UNDEFINED;
default:
return paramValue;
}
}

function _cleanSlot(slotName) {
if (utils.isStr(slotName)) {
return slotName.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
return '';
}

function _parseAdSlot(bid) {
bid.params.adUnit = '';
bid.params.adUnitIndex = '0';
bid.params.width = 0;
bid.params.height = 0;

bid.params.adSlot = _cleanSlot(bid.params.adSlot);

var slot = bid.params.adSlot;
var splits = slot.split(':');

slot = splits[0];
if (splits.length == 2) {
bid.params.adUnitIndex = splits[1];
}
splits = slot.split('@');
if (splits.length != 2) {
utils.logWarn('AdSlot Error: adSlot not in required format');
return;
}
bid.params.adUnit = splits[0];
splits = splits[1].split('x');
if (splits.length != 2) {
utils.logWarn('AdSlot Error: adSlot not in required format');
return;
}
bid.params.width = parseInt(splits[0]);
bid.params.height = parseInt(splits[1]);
}

function _initConf() {
var conf = {};
conf.pageURL = utils.getTopWindowUrl();
conf.refURL = utils.getTopWindowReferrer();
return conf;
}

function _handleCustomParams(params, conf) {
if (!conf.kadpageurl) {
conf.kadpageurl = conf.pageURL;
}

var key, value, entry;
for (key in CUSTOM_PARAMS) {
if (CUSTOM_PARAMS.hasOwnProperty(key)) {
value = params[key];
if (value) {
entry = CUSTOM_PARAMS[key];

if (typeof entry === 'object') {
// will be used in future when we want to process a custom param before using
// 'keyname': {f: function() {}}
value = entry.f(value, conf);
}

if (utils.isStr(value)) {
conf[key] = value;
} else {
utils.logWarn('PubMatic: Ignoring param : ' + key + ' with value : ' + CUSTOM_PARAMS[key] + ', expects string-value, found ' + typeof value);
}
}
}
}
return conf;
}

function _createOrtbTemplate(conf) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice! Would be great if we had a community ORTB adapter at some point...

return {
id: '' + new Date().getTime(),
at: AUCTION_TYPE,
cur: [CURRENCY],
imp: [],
site: {
page: conf.pageURL,
ref: conf.refURL,
publisher: {}
},
device: {
ua: navigator.userAgent,
js: 1,
dnt: (navigator.doNotTrack == 'yes' || navigator.doNotTrack == '1' || navigator.msDoNotTrack == '1') ? 1 : 0,
h: screen.height,
w: screen.width,
language: navigator.language
},
user: {},
ext: {}
};
}

function _createImpressionObject(bid, conf) {
return {
id: bid.bidId,
tagid: bid.params.adUnit,
bidfloor: _parseSlotParam('kadfloor', bid.params.kadfloor),
secure: window.location.protocol === 'https:' ? 1 : 0,
banner: {
pos: 0,
w: bid.params.width,
h: bid.params.height,
topframe: utils.inIframe() ? 0 : 1,
},
ext: {
pmZoneId: _parseSlotParam('pmzoneid', bid.params.pmzoneid)
}
};
}

export const spec = {
code: BIDDER_CODE,

/**
* Determines whether or not the given bid request is valid. Valid bid request must have placementId and hbid
*
* @param {BidRequest} bid The bid params to validate.
* @return boolean True if this is a valid bid, and false otherwise.
*/
isBidRequestValid: bid => {
if (bid && bid.params) {
if (!utils.isStr(bid.params.publisherId)) {
utils.logWarn('PubMatic Error: publisherId is mandatory and cannot be numeric. Call to OpenBid will not be sent.');
return false;
}
if (!utils.isStr(bid.params.adSlot)) {
utils.logWarn('PubMatic: adSlotId is mandatory and cannot be numeric. Call to OpenBid will not be sent.');
return false;
}
return true;
}
return false;
},

/**
* Make a server request from the list of BidRequests.
*
* @param {validBidRequests[]} - an array of bids
* @return ServerRequest Info describing the request to the server.
*/
buildRequests: validBidRequests => {
var conf = _initConf();
var payload = _createOrtbTemplate(conf);
validBidRequests.forEach(bid => {
_parseAdSlot(bid);
if (!(bid.params.adSlot && bid.params.adUnit && bid.params.adUnitIndex && bid.params.width && bid.params.height)) {
utils.logWarn('PubMatic: Skipping the non-standard adslot:', bid.params.adSlot, bid);
return;
}
conf.pubId = conf.pubId || bid.params.publisherId;
conf = _handleCustomParams(bid.params, conf);
conf.transactionId = bid.transactionId;
payload.imp.push(_createImpressionObject(bid, conf));
});

if (payload.imp.length == 0) {
return;
}

payload.site.publisher.id = conf.pubId.trim();
publisherId = conf.pubId.trim();
payload.ext.wrapper = {};
payload.ext.wrapper.profile = conf.profId || UNDEFINED;
payload.ext.wrapper.version = conf.verId || UNDEFINED;
payload.ext.wrapper.wiid = conf.wiid || UNDEFINED;
payload.ext.wrapper.wv = constants.REPO_AND_VERSION;
payload.ext.wrapper.transactionId = conf.transactionId;
payload.ext.wrapper.wp = 'pbjs';
payload.user.gender = (conf.gender ? conf.gender.trim() : UNDEFINED);
payload.user.geo = {};
payload.user.geo.lat = _parseSlotParam('lat', conf.lat);
payload.user.geo.lon = _parseSlotParam('lon', conf.lon);
payload.user.yob = _parseSlotParam('yob', conf.yob);
payload.device.geo = {};
payload.device.geo.lat = _parseSlotParam('lat', conf.lat);
payload.device.geo.lon = _parseSlotParam('lon', conf.lon);
payload.site.page = conf.kadpageurl.trim() || payload.site.page.trim();
payload.site.domain = _getDomainFromURL(payload.site.page);
return {
method: 'POST',
url: ENDPOINT,
data: JSON.stringify(payload)
};
},

/**
* Unpack the response from the server into a list of bids.
*
* @param {*} response A successful response from the server.
* @return {Bid[]} An array of bids which were nested inside the server.
*/
interpretResponse: (response, request) => {
const bidResponses = [];
try {
if (response.body && response.body.seatbid && response.body.seatbid[0] && response.body.seatbid[0].bid) {
response.body.seatbid[0].bid.forEach(bid => {
let newBid = {
requestId: bid.impid,
cpm: (parseFloat(bid.price) || 0).toFixed(2),
width: bid.w,
height: bid.h,
creativeId: bid.crid || bid.id,
dealId: bid.dealid,
currency: CURRENCY,
netRevenue: NET_REVENUE,
ttl: 300,
referrer: utils.getTopWindowUrl(),
ad: bid.adm
};
bidResponses.push(newBid);
});
}
} catch (error) {
utils.logError(error);
}
return bidResponses;
},

/**
* Register User Sync.
*/
getUserSyncs: syncOptions => {
if (syncOptions.iframeEnabled) {
return [{
type: 'iframe',
url: USYNCURL + publisherId
}];
} else {
utils.logWarn('PubMatic: Please enable iframe based user sync.');
}
}
};

registerBidder(spec);
53 changes: 53 additions & 0 deletions modules/pubmaticBidAdapter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Overview

```
Module Name: PubMatic Bid Adapter
Module Type: Bidder Adapter
Maintainer: [email protected]
```

# Description

Connects to PubMatic exchange for bids.

PubMatic bid adapter supports Banner currently.

# Sample Ad Unit: For Publishers
```
var adUnits = [
{
code: 'test-div',
sizes: [
[300, 250],
[728, 90]
],
bids: [{
bidder: 'pubmatic',
params: {
publisherId: '156209', // required
adSlot: 'pubmatic_test2@300x250', // required
pmzoneid: 'zone1, zone11', // optional
lat: '40.712775', // optional
lon: '-74.005973', // optional
yob: '1982', // optional
kadpageurl: 'www.test.com', // optional
gender: 'M', // optional
kadfloor: '0.50' // optional
}
}]
}
```

### Configuration

PubMatic recommends the UserSync configuration below. Without it, the PubMatic adapter will not able to perform user syncs, which lowers match rate and reduces monetization.

```javascript
pbjs.setConfig({
userSync: {
iframeEnabled: true,
enabledBidders: ['pubmatic'],
syncDelay: 6000
}});
```
Note: Combine the above the configuration with any other UserSync configuration. Multiple setConfig() calls overwrite each other and only last call for a given attribute will take effect.
Loading