· 7 years ago · Mar 16, 2018, 08:02 PM
1/**
2 * The below requires two bits of setup in Postman:
3 *
4 * 1. An environment variable named `TRIP_COM_API_CLIENT_SECRET` set to your client secret for the API
5 * 2. A request parameter named `signature` set to the value `{{_SIGNATURE}}` - this will be set by this script
6 */
7
8
9// Mostly copy-pastad from Stack Overflow since Postman doesn't seem to offer an out-of-the-box
10// library for URL query param parsing, go figure
11function parseQuery(url) {
12 const queryString = _.last(url.split('?'))
13 const query = {}
14 const pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&')
15 for (let i = 0; i < pairs.length; i++) {
16 const pair = pairs[i].split('=')
17 query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')
18 }
19 return query
20}
21
22// Grab secret key from env vars
23const SECRET_KEY = postman.getEnvironmentVariable('TRIP_COM_API_CLIENT_SECRET')
24if (!SECRET_KEY) { throw new Error('Missing required environment variable SECRET_KEY') }
25
26// Get all URL params except for the to-be-populated `signature`
27const parsedQueryString = parseQuery(request.url)
28delete parsedQueryString['signature']
29
30// Assume the POST body is a JSON object and grab key-value params from that too
31const body = JSON.parse(request.data)
32const allParams = Object.assign({}, parsedQueryString)
33for (const key in body) {
34 const val = body[key]
35 const isList = _.isArray(val)
36 allParams[key] = isList ? val.join('') : val
37}
38
39// Create the signature payload (sort all parameter keys, concatenate them without '=' or '&'
40const payload = _(allParams).keys().sort().map(key => `${key}${allParams[key]}`).join('') + SECRET_KEY
41
42// HMAC-SHA256 the payload
43const hash = CryptoJS.HmacSHA256(payload, SECRET_KEY).toString(CryptoJS.enc.Base64)
44
45// URL encode and assign to _SIGNATURE variable
46const signature = encodeURIComponent(hash)
47postman.setEnvironmentVariable('_SIGNATURE', signature)