-
Notifications
You must be signed in to change notification settings - Fork 23
/
adWordsObject.js
84 lines (71 loc) · 2.19 KB
/
adWordsObject.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// require external modules
var
_ = require('lodash'),
request = require('request');
// define abstract AdWords object
function AdWordsObject(options) {
var self = this;
// set up rational defaults
if (!options) options = {};
_.defaults(options, {
ADWORDS_CLIENT_ID: process.env.ADWORDS_CLIENT_ID,
ADWORDS_CLIENT_CUSTOMER_ID: process.env.ADWORDS_CLIENT_CUSTOMER_ID,
ADWORDS_DEVELOPER_TOKEN: process.env.ADWORDS_DEVELOPER_TOKEN,
ADWORDS_REFRESH_TOKEN: process.env.ADWORDS_REFRESH_TOKEN,
ADWORDS_SECRET: process.env.ADWORDS_SECRET,
ADWORDS_USER_AGENT: process.env.ADWORDS_USER_AGENT,
verbose: false
});
// check if all credentials are supplied
if (
!options.ADWORDS_CLIENT_ID ||
!options.ADWORDS_CLIENT_CUSTOMER_ID ||
!options.ADWORDS_DEVELOPER_TOKEN ||
!options.ADWORDS_REFRESH_TOKEN ||
!options.ADWORDS_SECRET ||
!options.ADWORDS_USER_AGENT
) {
throw (new Error('googleads-node-lib not configured correctly'));
}
self.options = options;
self.credentials = null;
self.tokenUrl = 'https://www.googleapis.com/oauth2/v3/token';
self.verbose = self.options.verbose;
self.version = 'v201509';
self.refresh = function(done) {
// check if current credentials haven't expired
if (self.credentials && Date.now() < self.credentials.expires) {
// behave like an async
setTimeout(function() {done(null);}, 0);
return;
} else {
// throw away cached client
self.client = null;
var qs = {
refresh_token: self.options.ADWORDS_REFRESH_TOKEN,
client_id: self.options.ADWORDS_CLIENT_ID,
client_secret: self.options.ADWORDS_SECRET,
grant_type: 'refresh_token'
};
request.post(
{
qs: qs,
url: self.tokenUrl
},
function(error, response, body) {
self.credentials = JSON.parse(body);
self.credentials.issued = Date.now();
self.credentials.expires = self.credentials.issued -
self.credentials.expires_in;
done(error);
}
);
return;
}
};
self.setVerbose = function(flag) {
self.verbose = flag;
return self;
};
}
module.exports = (AdWordsObject);