Created
August 7, 2015 07:04
-
-
Save pmatsinopoulos/f502c45687d4307ee6bc to your computer and use it in GitHub Desktop.
Example of sending a signed request to Book&Table Mobile API when POST with body data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rest-client' | |
user_id = 5 | |
secret_key = 'secret key of user with id 5' | |
tutor_id = 105 | |
timestamp = Time.now.utc.httpdate # Example: "Mon, 03 Aug 2015 20:15:56 GMT" | |
def calculate_canonical_string(content_type, content_md5, path, timestamp) | |
[ content_type, | |
content_md5, | |
path, | |
timestamp | |
].join(",") | |
end | |
def hmac_signature(content_type, content_md5, path, timestamp, secret_key) | |
canonical_string = calculate_canonical_string(content_type, content_md5, path, timestamp) | |
digest = OpenSSL::Digest.new('sha1') | |
hmac_digest = OpenSSL::HMAC.digest(digest, secret_key, canonical_string) | |
Base64.strict_encode64(hmac_digest) | |
end | |
content_type = 'application/json' | |
payload = { | |
"contact_tutor" => { | |
"when" => 'Immediately', | |
"standard_subject_id" => 101, | |
"student_grade" => '1', | |
"meeting_frequency" => "Once or Twice a Month", | |
"meeting_days" => ["Sunday", "Saturday"], | |
"meeting_times" => ["Late afternoon (3 - 6pm)"], | |
"number_of_students" => 2, | |
"state_id" => 43, | |
"zip_code" => "19001", | |
"first_name" => 'First name', | |
"last_name" => 'Last Name', | |
"mobile_phone" => '3823828382', | |
"message" => "Can you please come back to me?" | |
} | |
} | |
path_with_params = "/mobile/1.0/contact_tutor/#{tutor_id}" | |
calculated_md5 = Digest::MD5.base64digest(payload.to_json) | |
signature = hmac_signature(content_type, calculated_md5, path_with_params, timestamp, secret_key) | |
headers = { | |
'X-BOOK-AND-TABLE-API-KEY-TYPE' => 'IOS_IPHONE', | |
'X-BOOK-AND-TABLE-API-KEY' => ENV['BOOK_AND_TABLE_API_KEY_IOS_IPHONE'], | |
'Accept' => 'application/json', | |
'Content-Type' => content_type, | |
'Content-MD5' => calculated_md5, | |
'Date' => timestamp, | |
'Authorization' => "APIAuth #{user_id}:#{signature}" | |
} | |
request = RestClient::Request.new(url: "http://localhost:3000#{path_with_params}", | |
headers: headers, | |
method: :post, | |
payload: payload.to_json) | |
response = nil | |
begin | |
response = request.execute | |
rescue RestClient::UnprocessableEntity => ex | |
puts ex.inspect | |
exit 1 | |
end | |
response_decoded = ActiveSupport::JSON.decode(response.body) | |
puts "The results of the request are: #{response_decoded.inspect}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment