-
Notifications
You must be signed in to change notification settings - Fork 1
/
mailersend.ex
93 lines (85 loc) · 2.25 KB
/
mailersend.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
defmodule Webhoox.Adapter.Mailersend do
@moduledoc """
Mailersend Adapter
Note: Must set up custom parser to set raw_body:
- https://stackoverflow.com/questions/41510957/read-the-raw-body-from-a-plug-connection-after-parsers-in-elixir
- https://hexdocs.pm/plug/Plug.Parsers.html#module-custom-body-reader
"""
import Webhoox.Authentication
import Webhoox.Utility.Parser
@behaviour Webhoox.Adapter
def handle_webhook(conn, handler, opts) do
signing_secret = Keyword.fetch!(opts, :signing_secret)
case valid_signature?(:base16, conn, signing_secret, "signature") do
true ->
conn.body_params
|> normalize_params()
|> handler.process()
{:ok, conn}
_ ->
{:error, conn}
end
end
@doc """
Handle Mailersend v1 webhook type
"""
def normalize_params(
email = %{
"created_at" => timestamp,
"data" => %{
"email" => %{
"from" => sender,
"message" => %{
"id" => message_id
},
"recipient" => %{
"email" => to
},
"subject" => subject
}
},
"type" => event
}
) do
%Webhoox.Webhook.Email{
message_id: message_id,
event: event,
sender: sender,
to: parse_email_recipients(to),
from: parse_email_address(sender),
subject: subject,
timestamp: parse_timestamp(timestamp),
raw_params: email
}
end
def normalize_params(
email = %{
"created_at" => timestamp,
"data" => %{
"from" => %{"email" => sender},
"html" => html,
"text" => text,
"id" => message_id,
"subject" => subject,
"recipients" => %{
"to" => %{"raw" => to}
}
},
"type" => event
}
) do
%Webhoox.Webhook.Email{
message_id: message_id,
event: event,
sender: sender,
to: parse_email_recipients(to),
from: parse_email_address(sender),
subject: subject,
html: html,
text: text,
timestamp: parse_timestamp(timestamp),
raw_params: email
}
end
def normalize_params(_), do: nil
end