Created
July 3, 2017 19:24
-
-
Save subomi/2f67c79ed358afef07f1fc20097acb22 to your computer and use it in GitHub Desktop.
A small events data type to handle paystack payments events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const EventEmitter = require('events').EventEmitter; | |
const util = require('util'); | |
module.export = eventsCreator; | |
const eventNames; | |
function eventsCreator(object) { | |
if(!object) throw new Error("Agent object not found!"); | |
if(!object.key) throw new Error("Please ensure that you've called the agent object"); | |
// cache quickly | |
eventNames = object.events; | |
events.bind(object); | |
EventEmitter.call(events); | |
util.inherits(events, EventEmitter) | |
return events; | |
} | |
function events(req, res, next) { | |
let body = req.body; | |
let eventType = body.event; | |
if(!eventNames) { | |
if(process.NODE_ENV === "development") console.log("You are not listing the events you really want to listen to!") | |
if(!(eventType in eventNames)) { | |
next(new Error("Event not supported!")); | |
} | |
} | |
var hash = crypto.createHmac('sha512', secret).update(JSON.stringify(body)).digest('hex'); | |
if(hash === req.headers['x-paystack-signature']) { | |
// Valid | |
res.send(200); | |
events.emit(eventType, req, next); | |
} | |
} | |
events.setHandler = function(eventType, callback) { | |
this.addListener(eventType, callback); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Usage: