Created
January 7, 2018 10:48
-
-
Save andrey-kazakov/1a54a4d5b5b8b51dd9c23ed910cac6ca to your computer and use it in GitHub Desktop.
Simple service for interaction with Justclick API in Ruby (depends on Faraday)
This file contains 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
module Justclick::Api | |
class Interactor | |
def invoke_method(method, data, allowed_codes: [0, 601]) | |
check_response_status( | |
ParamsDecoder.decode( | |
http_client.post( | |
[ | |
"http://", | |
Rails.application.secrets.justclick[:user], | |
".justclick.ru/api/", | |
method | |
].join, | |
data | |
).body | |
), | |
allowed_codes | |
) | |
end | |
private | |
def check_response_status(response, allowed_codes) | |
message = [response.error_code, response.error_text].join(": ") | |
raise WrongStatusError, message unless allowed_codes.include?(response.error_code) | |
response | |
end | |
def http_client | |
@client ||= Faraday.new( | |
request: { | |
params_encoder: ParamsEncoder | |
} | |
) | |
end | |
class WrongStatusError < StandardError; end | |
class InvalidSignatureError < StandardError; end | |
module ParamsEncoder | |
module_function | |
# NOTICE | |
# arrays AREN'T supported | |
# nils AREN'T supported | |
# (both will result in failed signature check) | |
def encode(input) | |
output = Faraday::NestedParamsEncoder.encode(input) | |
[output, "hash=" + make_signature(output)].join("&") | |
end | |
# md5("$params::$user_id::$secret") | |
def make_signature(input) | |
Digest::MD5.hexdigest( | |
[ | |
input, | |
Rails.application.secrets.justclick[:user], | |
Rails.application.secrets.justclick[:api_secret] | |
].join("::") | |
) | |
end | |
end | |
module ParamsDecoder | |
module_function | |
def decode(input) | |
hash = JSON.parse(input) | |
return Hashie::Mash.new(hash) if signature_valid?(hash) | |
raise InvalidSignatureError, input | |
end | |
# md5("$code::$text::$secret") | |
def signature_valid?(hash) | |
ActiveSupport::SecurityUtils.secure_compare( | |
hash["hash"], | |
Digest::MD5.hexdigest( | |
[ | |
hash["error_code"], | |
hash["error_text"], | |
Rails.application.secrets.justclick[:api_secret] | |
].join("::") | |
) | |
) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment