Skip to content

Instantly share code, notes, and snippets.

@ryanwinchester
Last active November 8, 2021 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanwinchester/ab49855e9acb7352507b8fa92ffe69d0 to your computer and use it in GitHub Desktop.
Save ryanwinchester/ab49855e9acb7352507b8fa92ffe69d0 to your computer and use it in GitHub Desktop.
Twilio signature module
defmodule TwilioSignature do
@moduledoc """
Twilio signatures module.
"""
@doc """
Generate the Twilio signature from a request.
See: https://www.twilio.com/docs/usage/security#validating-requests
## Example
iex> url = "https://mycompany.com/myapp.php?foo=1&bar=2"
iex> params = %{
...> "CallSid" => "CA1234567890ABCDE",
...> "From" => "+12349013030",
...> "To" => "+18005551212",
...> "Caller" => "+12349013030",
...> "Digits" => "1234"
...> }
iex> TwilioSignature.generate(url, params, "12345")
"0/KCTR6DLpKmkAf8muzZqo1nDgQ="
"""
@spec generate(String.t(), map(), String.t()) :: String.t()
def generate(url, params, secret) do
sorted_params_iolist =
params
|> Enum.sort_by(fn {k, v} -> [k, v] end)
|> List.flatten()
[url | sorted_params_iolist]
|> then(&:crypto.mac(:hmac, :sha, secret, &1))
|> Base.encode64()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment