Skip to content

Instantly share code, notes, and snippets.

@jonnyom
Last active August 25, 2022 10:19
Show Gist options
  • Save jonnyom/a730f07b1beb680366bd73d0fa5feb28 to your computer and use it in GitHub Desktop.
Save jonnyom/a730f07b1beb680366bd73d0fa5feb28 to your computer and use it in GitHub Desktop.
## Running this file locally
# Save this file to intercom_webhooks.rb
# In the same directory as the file type "gem install sinatra" and "gem install json" into your command line.
# Install Ngrok (Webhook testing software) blogpost on using it here: https://www.intercom.com/blog/how-to-get-up-and-running-with-messenger-apps-using-ngrok/
# In your command line type "ruby intercom_webhook.rb"
# Once ngrok is installed you can type "ngrok http 4567" in your command line to start Ngrok.
# Now create a new webhook in your developer hub (app.intercom.com/developers/_/webhooks) pointing to the URL that Ngrok gives you
# Save the webhook once you have selected the topic you want notifications for
# Trigger the action to send the webhook notification. For example closing a conversation
require 'sinatra'
require 'json'
WH_SECRET = "<YOUR-SECRET-HERE>" # If you don't have a secret remove this line
APP_URL_REGEX = /\/apps\/(?<app_id>\w+)/
# Authenticate requests
def check_signature(payload_body)
wh_signature = request.env['HTTP_X_HUB_SIGNATURE']
puts "Received signature: #{wh_signature}"
if wh_signature.nil? || wh_signature.empty?
puts "No signature received with the webhook."
else
computed_signature = 'sha1=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'), WH_SECRET, payload_body).to_s
puts "Calculated signature: #{computed_signature}"
puts "Signatures match: #{wh_signature === computed_signature}"
return halt 401, "Invalid signature!" if !(wh_signature === computed_signature)
end
end
def parse_details(url)
match = url.match(APP_URL_REGEX)
{
app_id: match[:app_id]
}
end
post '/' do
# First getting the payload as simple string, we need it to compute the signature
payload_body = request.body.read
# Check the signature
check_signature(payload_body)
# Parsing the payload to JSON to be able to get the values
payload = JSON.parse(payload_body)
wh_topic = payload["topic"]
wh_data = payload["data"]
links = wh_data["item"]["links"]
conversation_id = wh_data["item"]["id"]
puts "Topic: #{wh_topic}"
puts "Data: #{wh_data.to_json}"
puts "Payload: #{payload}"
puts ""
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment