Skip to content

Instantly share code, notes, and snippets.

@igorrendulic
Last active December 3, 2017 22:19
Show Gist options
  • Save igorrendulic/c1d30c5729420459d2d9945d71441607 to your computer and use it in GitHub Desktop.
Save igorrendulic/c1d30c5729420459d2d9945d71441607 to your computer and use it in GitHub Desktop.
MailGun Webhook Handler
public class MailgunWebhook extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
resp.setContentType("application/json");
String token = null;
String timestamp = null;
String signature = null;
String event = null;
String customVar = null;
String contentType = req.getHeader("Content-Type");
if (contentType != null && contentType.contains("multipart/form")) {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List<FileItem> items = upload.parseRequest(req);
if (items != null) {
for (FileItem item : items) {
if (item.getFieldName() != null) {
if (item.getFieldName().equals("signature")) {
signature = item.getString();
}
if (item.getFieldName().equals("token")) {
token = item.getString();
}
if (item.getFieldName().equals("timestamp")) {
timestamp = item.getString();
}
if (item.getFieldName().equals("event")) {
event = item.getString();
}
if (item.getFieldName().equals("custom_var")) {
customVar = item.getString();
}
}
}
}
} else {
signature = req.getParameter("signature");
token = req.getParameter("token");
timestamp = req.getParameter("timestamp");
event = req.getParameter("event");
customVar = req.getParameter("custom_var");
}
if (token != null && timestamp != null && signature != null) {
boolean isValid = MailGun.isSignatureValid(token, Long.valueOf(timestamp), signature);
if (!isValid) {
sendErrorResponse(resp,"Invalid signature");
return;
}
handleEvent(event, customVar);
}
} catch (Exception e) {
sendErrorResponse(resp, e.getMessage());
return;
}
}
/**
* Handling webhook events
*
* @param event
* @param customVar
* @throws Exception
*/
private void handleEvent(String event, String customVar) throws Exception {
// track delivery for campaign
if (event != null && customVar != null) {
// code to handle the event
}
}
/**
* Constructing error reponse
* @param resp
* @param message
* @throws IOException
*/
private void sendErrorResponse(HttpServletResponse resp, String message) throws IOException {
resp.setStatus(Status.BAD_REQUEST.getStatusCode());
resp.getWriter().write(new JSONObject().put("error", message).toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment