Mandrill é um serviço para disparo de emails transacionais, ele possui relatórios e você pode receber os eventos de cada mensagem (enviado, aberto, click em link, etc) enviada via Webhook.
Procurando uma forma de autenticar o Webhook do Mandrill com Python, o qual eu já havia feito com PHP, eu encontrei esse artigo que mostrava como fazer utilizando o framework Webapp2 e usando uma versão 2.7 do Python. Como eu utilizo Flask com Python 3.4, tive que fazer algumas modificações, mas consegui fazer funcionar.
Segue o trecho de código que estou utilizando:
def calc_mandrill_signature(raw, key):
import hashlib
import hmac
import base64
digest = hmac.new(key.encode('utf-8'), raw.encode('utf-8'), hashlib.sha1).digest()
hashed = base64.encodestring(digest).decode("utf-8").rstrip('\n')
return hashed
def verify_mandrill_signature(request):
'''
Mandrill includes an additional HTTP header with webhook POST requests,
X-Mandrill-Signature, which will contain the signature for the request.
To verify a webhook request, generate a signature using the same key
that Mandrill uses and compare that to the value of the
X-Mandrill-Signature header.
:return: True if verified valid
'''
mandrill_signature = request.headers['X-Mandrill-Signature']
mandrill_key = 'aqui vai a API key do seu webhook'
signed_data = request.url
sorted_key = sorted(request.form)
for k in sorted_key:
signed_data += k
signed_data += request.form[k]
expected_signature = calc_mandrill_signature(signed_data, mandrill_key)
return expected_signature == mandrill_signature
@app.route('/webhook', methods=['POST'])
def event_webhook():
if not verify_mandrill_signature(request):
abort(403)
import json
data = json.loads(request.form['mandrill_events'])
for e in data:
'''
Insira o que você quiser fazer com os resultados dos eventos...
'''