Skip to content

Instantly share code, notes, and snippets.

@cmlewis
Last active August 29, 2018 19:05
Show Gist options
  • Save cmlewis/fc94a5a73a0b1762cd55825f46c188f9 to your computer and use it in GitHub Desktop.
Save cmlewis/fc94a5a73a0b1762cd55825f46c188f9 to your computer and use it in GitHub Desktop.
Emarsys API Samples - Node.js
Emarsys API Samples - Node.js
# Logs
logs
*.log
npm-debug.log*
# Dependency directory
node_modules
# Optional npm cache directory
.npm
const rp = require('request-promise'),
whilst = require('async/whilst'),
crypto = require('crypto'),
iso8601 = require('iso8601'),
_ = require('lodash');
module.exports = class API {
constructor(user,pass) {
this.user = user;
this.pass = pass;
this.url = 'https://api.emarsys.net/api/v2';
}
base64Sha1 (str) {
let hexDigest = crypto.createHash('sha1')
.update(str)
.digest('hex');
return new Buffer(hexDigest).toString('base64');
}
getWsseHeader (user, pass) {
let nonce = crypto.randomBytes(16).toString('hex');
let timestamp = iso8601.fromDate(new Date());
let digest = this.base64Sha1(nonce + timestamp + pass);
return 'UsernameToken Username="'+ user +'", PasswordDigest="'+ digest +'", Nonce="'+ nonce +'", Created="'+ timestamp +'"';
}
parse (body,response) {
body = JSON.parse(body);
if(body.replyCode != 0) {
throw new Error(body.replyText);
}
return body;
}
setOptions (uri, optObj = {}) {
uri = uri.substring(0,1) === '/' ? uri : '/' + uri;
return Object.assign({
url: this.url + uri,
headers: {
'Content-Type': 'application/json',
'X-WSSE': this.getWsseHeader(this.user, this.pass)
},
transform: this.parse,
transform2xxOnly: true
}, optObj);
}
get (uri, data) {
return rp.get( this.setOptions(uri, {qs: data}) );
}
put (uri, data) {
return rp.put( this.setOptions(uri, {body: JSON.stringify(data)}) );
}
post (uri, data) {
return rp.post( this.setOptions(uri, {body: JSON.stringify(data)}) );
}
}
/**
* Author Christy Lewis
* Tester for Emarsys API calls
*
* Basic Node.js example, including how to authenticate with your API key and secret.
* Steps to run:
* Download files.
* Update creds with your API key and secret.
* Open cmd or terminal window in folder.
* Run npm install
* Run node emarsys_api_tester.js
* Open browser to http://localhost:8080
* Monitor console/terminal window for responses.
*/
let request = require('request'),
API = require('./emarsys_api_helper.js'),
http = require('http');
const creds = {
user: 'yourAPIkey',
pass: 'yourAPIsecret'
};
http.createServer(function(request, response) {
// Status code
response.writeHead(200);
console.log('Starting API Tester');
const api = new API(creds.user, creds.pass);
/***************
* CONTACTS
***************/
// Gets all contacts.
// (WARNING: ALL contacts. Add field IDs with criteria to narrow down results.)
// api.get('/contact/query/', {
// return: '3',
// // '33941': '',
// excludeempty: true
// })
// Create contact
// api.post('/contact', {
// "key_id" : "3",
// "1" : "John",
// "2" : "Doe",
// "3" : "[email protected]"
// })
/***************
* SETTINGS
***************/
// Gets suite settings for the account
api.get('/settings/', {})
/***************
* OLD RDS
***************/
// Insert record
// api.post('/rds/tables/wishlist/records', [{
// "SKU": "12345",
// "Name": "Shoes - Black",
// "PriceWhenAdded": "59.99",
// "DateAdded": new Date()
// }]
// )
.then(function(body){
console.log("RESPONSE:", body);
// console.log(job.attrs.name, body.data);
// console.log(job.attrs.name, body.data.result);
})
.catch(function(err){
console.log('ERROR:', err.message);
})
response.end('Done.');
}).listen(8080);
console.log('Server running at http://localhost:8080');
{
"name": "emarsys-api-tester",
"version": "1.0.0",
"description": "Node.js examples for Emarsys API",
"main": "api_tester.js",
"scripts": {
"start": "node emarsys_api_tester.js"
},
"author": "[email protected]",
"dependencies": {
"async": "^2.6.1",
"crypto": "^1.0.1",
"http": "^0.0.0",
"iso8601": "^1.1.1",
"lodash": "^4.17.10",
"request": "^2.87.0",
"request-promise": "^4.2.2"
},
"devDependencies": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment