Class: Simplify::PaymentsApi
- Inherits:
-
Object
- Object
- Simplify::PaymentsApi
- Defined in:
- lib/simplify/paymentsapi.rb
Constant Summary collapse
- @@JWS_NUM_HEADERS =
7
- @@JWS_ALGORITHM =
'HS256'
- @@JWS_TYPE =
'JWS'
- @@JWS_HDR_UNAME =
'uname'
- @@JWS_HDR_URI =
'api.simplifycommerce.com/uri'
- @@JWS_HDR_TIMESTAMP =
'api.simplifycommerce.com/timestamp'
- @@JWS_HDR_NONCE =
'api.simplifycommerce.com/nonce'
- @@JWS_HDR_TOKEN =
"api.simplifycommerce.com/token"
- @@JWS_TIMESTAMP_MAX_DIFF =
5 minutes
1000 * 60 * 5
- @@HTTP_SUCCESS =
200
- @@HTTP_REDIRECTED =
302
- @@HTTP_UNAUTHORIZED =
401
- @@HTTP_NOT_FOUND =
404
- @@HTTP_NOT_ALLOWED =
405
- @@HTTP_BAD_REQUEST =
400
- @@HTTP_SERVER_ERROR =
500
Class Method Summary collapse
- .build_url(base_url, type, action, objectMap) ⇒ Object
- .check_auth(auth) ⇒ Object
- .create_auth_object(auth) ⇒ Object
- .execute(type, action, objectMap, auth) ⇒ Object
- .get_base_url(public_key) ⇒ Object
- .get_oauth_error(msg, error_code, error_desc) ⇒ Object
- .jws_auth_error(reason) ⇒ Object
- .jws_decode(params, auth) ⇒ Object
- .jws_encode(auth, url, objectMap, hasPayload) ⇒ Object
- .jws_sign(private_key, msg) ⇒ Object
- .jws_verify_header(header, url, public_key) ⇒ Object
- .jws_verify_signature(private_key, msg, crypto) ⇒ Object
- .jws_verify_timestamp(ts) ⇒ Object
- .live_key?(public_key) ⇒ Boolean
- .oauth_jws_encode(auth, url, props) ⇒ Object
- .send_auth_request(props, context, auth) ⇒ Object
- .urlsafe_decode64(s) ⇒ Object
-
.urlsafe_encode64(s) ⇒ Object
Base64.urlsafe_encode64()/urlsafe_decode64() is not available in ruby 1.8.
Class Method Details
.build_url(base_url, type, action, objectMap) ⇒ Object
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 |
# File 'lib/simplify/paymentsapi.rb', line 326 def self.build_url(base_url, type, action, objectMap) parts = [] parts << base_url parts << type parts << case action when 'show', 'update', 'delete' then [URI::encode(objectMap["id"].to_s)] end url = parts.flatten().join('/') query = Array.new if action == "list" and objectMap != nil then if (objectMap['max']) query << "max=#{objectMap['max']}" end if (objectMap['offset']) query << "offset=#{objectMap['offset']}" end if (objectMap['sorting']) then objectMap['sorting'].each { |k, v| query << "sorting[#{URI::encode(k.to_s)}]=#{URI::encode(v.to_s)}" } end if (objectMap['filter']) then objectMap['filter'].each { |k, v| query << "filter[#{URI::encode(k.to_s)}]=#{URI::encode(v.to_s)}" } end end if query.size > 0 then url = url + "?" + query.join('&') end return url end |
.check_auth(auth) ⇒ Object
159 160 161 162 163 164 165 166 167 168 169 170 171 |
# File 'lib/simplify/paymentsapi.rb', line 159 def self.check_auth(auth) if auth == nil raise ArgumentError.new("Missing authentication object") end if auth.public_key == nil raise ArgumentError.new("Must have a valid public key to connect to the API") end if auth.private_key == nil raise ArgumentError.new("Must have a valid private key to connect to the API") end end |
.create_auth_object(auth) ⇒ Object
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/simplify/paymentsapi.rb', line 131 def self.create_auth_object(auth) case auth.length when 0 auth_obj = Authentication.new(:public_key => Simplify::public_key, :private_key => Simplify::private_key) when 1 auth_obj = auth[0] if ! auth_obj.is_a? Authentication raise ArgumentError.new("Invalid Authentication object passed") end when 2 # Deprecated case where public and private keys are passed public_key = auth[0] if public_key == nil public_key = Simplify::public_key end private_key = auth[1] if private_key == nil private_key = Simplify::private_key end auth_obj = Authentication.new(:public_key => public_key, :private_key => private_key) else raise ArgumentError.new("Invalid authentication arguments passed") end return auth_obj end |
.execute(type, action, objectMap, auth) ⇒ Object
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
# File 'lib/simplify/paymentsapi.rb', line 174 def self.execute(type, action, objectMap, auth) check_auth(auth) content_type = 'application/json' url = build_url(get_base_url(auth.public_key), type, action, objectMap) signature = jws_encode(auth, url, objectMap, action == 'update' || action == 'create') opts = case action when 'show', 'projections' then { :method => 'GET', :headers => { :authorization => "JWS #{signature}" } } when 'list' then { :method => 'GET', :headers => { :authorization => "JWS #{signature}" } } when 'update' then { :method => 'PUT', :payload => signature } when 'create' then { :method => 'POST', :payload => signature } when 'delete' then { :method => 'DELETE', :headers => { :authorization => "JWS #{signature}" } } end user_agent = "Ruby-SDK/#{Constants::version}" if Simplify::user_agent != nil user_agent = "#{user_agent} #{Simplify::user_agent}" end opts = opts.merge({ :url => url, :headers => { 'Content-Type' => content_type, 'Accept' => 'application/json', 'User-Agent' => user_agent }.merge(opts[:headers] || {}) }) begin response = RestClient::Request.execute(opts) JSON.parse(response.body) rescue RestClient::Exception => e begin errorData = JSON.parse(e.response.body) rescue JSON::ParserError => e2 raise ApiException.new("Unknown error", nil, nil) end if e.response.code == @@HTTP_REDIRECTED raise BadRequestException.new("Unexpected response code returned from the API, have you got the correct URL?", e.response.code, errorData) elsif e.response.code == @@HTTP_BAD_REQUEST raise BadRequestException.new("Bad request", e.response.code, errorData) elsif e.response.code == @@HTTP_UNAUTHORIZED raise AuthenticationException.new("You are not authorized to make this request. Are you using the correct API keys?", e.response.code, errorData) elsif e.response.code == @@HTTP_NOT_FOUND raise ObjectNotFoundException.new("Object not found", e.response.code, errorData) elsif e.response.code == @@HTTP_NOT_ALLOWED raise NotAllowedException.new("Operation not allowed", e.response.code, errorData) elsif e.response.code < @@HTTP_SERVER_ERROR raise BadRequestException.new("Bad request", e.response.code, errorData) else raise SystemException.new("An unexpected error has been raised. Looks like there's something wrong at our end.", e.response.code, errorData) end end end |
.get_base_url(public_key) ⇒ Object
366 367 368 369 370 371 372 373 |
# File 'lib/simplify/paymentsapi.rb', line 366 def self.get_base_url(public_key) if live_key?(public_key) return Simplify::api_base_live_url end return Simplify::api_base_sandbox_url end |
.get_oauth_error(msg, error_code, error_desc) ⇒ Object
322 323 324 |
# File 'lib/simplify/paymentsapi.rb', line 322 def self.get_oauth_error(msg, error_code, error_desc) error_data = {'error' => {'code' => 'oauth_error', 'message' => "#{msg}, error code '#{error_code}', description '#{error_desc}'"}} end |
.jws_auth_error(reason) ⇒ Object
518 519 520 |
# File 'lib/simplify/paymentsapi.rb', line 518 def self.jws_auth_error(reason) raise AuthenticationException.new("JWS authentication failure: #{reason}", nil, nil) end |
.jws_decode(params, auth) ⇒ Object
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 |
# File 'lib/simplify/paymentsapi.rb', line 418 def self.jws_decode(params, auth) check_auth(auth) payload = params['payload'] if payload == nil raise ArgumentError.new("Event data is missing payload") end begin payload.strip! data = payload.split('.') if data.size != 3 jws_auth_error("Incorrectly formatted JWS message"); end msg = "#{data[0]}.#{data[1]}" header = urlsafe_decode64(data[0]) payload = urlsafe_decode64(data[1]) jws_verify_header(header, params['url'], auth.public_key) if !jws_verify_signature(auth.private_key, msg, data[2]) jws_auth_error("JWS signature does not match") end return JSON.parse(payload) resue Exception => e jws_auth_error("Exception during JWS decoding: #{e}") end jws_auth_error("JWS decode failed") end |
.jws_encode(auth, url, objectMap, hasPayload) ⇒ Object
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 |
# File 'lib/simplify/paymentsapi.rb', line 375 def self.jws_encode(auth, url, objectMap, hasPayload) jws_hdr = {'typ' => @@JWS_TYPE, 'alg' => @@JWS_ALGORITHM, 'kid' => auth.public_key, @@JWS_HDR_URI => url, @@JWS_HDR_TIMESTAMP => Time.now.to_i * 1000, @@JWS_HDR_NONCE => SecureRandom.hex } token = auth.access_token if token != nil && !token.empty? jws_hdr[@@JWS_HDR_TOKEN] = token end hdr = urlsafe_encode64(jws_hdr.to_json) payload = '' if (hasPayload) then payload = urlsafe_encode64(objectMap.to_json) end msg = hdr + '.' + payload return msg + '.' + jws_sign(auth.private_key, msg) end |
.jws_sign(private_key, msg) ⇒ Object
453 454 455 |
# File 'lib/simplify/paymentsapi.rb', line 453 def self.jws_sign(private_key, msg) urlsafe_encode64(HMAC::SHA256.digest(Base64.decode64(private_key), msg)) end |
.jws_verify_header(header, url, public_key) ⇒ Object
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 |
# File 'lib/simplify/paymentsapi.rb', line 458 def self.jws_verify_header(header, url, public_key) hdr = JSON.parse(header) if hdr.size != @@JWS_NUM_HEADERS jws_auth_error("Incorrect number of JWS header parameters - found #{hdr.size} required #{@@JWS_NUM_HEADERS}") end if hdr['alg'] != @@JWS_ALGORITHM jws_auth_error("Incorrect algorithm - found #{hdr['alg']} required #{@@JWS_ALGORITHM}") end if hdr['typ'] != @@JWS_TYPE jws_auth_error("Incorrect type - found #{hdr['typ']} required #{@@JWS_TYPE}") end if hdr['kid'] == nil jws_auth_error("Missing Key ID") end if hdr['kid'] != public_key if live_key?(public_key) jws_auth_error("Invalid Key ID") end end if hdr[@@JWS_HDR_URI] == nil jws_auth_error("Missing URI") end if url != nil && hdr[@@JWS_HDR_URI] != url jws_auth_error("Incorrect URL - found #{hdr[@@JWS_HDR_URI]} required #{url}") end if hdr[@@JWS_HDR_TIMESTAMP] == nil jws_auth_error("Missing timestamp") end if !(hdr[@@JWS_HDR_TIMESTAMP]) jws_auth_error("Invalid timestamp") end if hdr[@@JWS_HDR_NONCE] == nil jws_auth_error("Missing nonce") end if hdr[@@JWS_HDR_UNAME] == nil jws_auth_error("Missing username header") end end |
.jws_verify_signature(private_key, msg, crypto) ⇒ Object
509 510 511 |
# File 'lib/simplify/paymentsapi.rb', line 509 def self.jws_verify_signature(private_key, msg, crypto) return crypto == jws_sign(private_key, msg) end |
.jws_verify_timestamp(ts) ⇒ Object
514 515 516 |
# File 'lib/simplify/paymentsapi.rb', line 514 def self.(ts) return (Time.now.to_i * 1000 - ts.to_i).abs < @@JWS_TIMESTAMP_MAX_DIFF end |
.live_key?(public_key) ⇒ Boolean
522 523 524 |
# File 'lib/simplify/paymentsapi.rb', line 522 def self.live_key?(public_key) return public_key.start_with?("lvpb") end |
.oauth_jws_encode(auth, url, props) ⇒ Object
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 |
# File 'lib/simplify/paymentsapi.rb', line 401 def self.oauth_jws_encode(auth, url, props) jws_hdr = {'typ' => @@JWS_TYPE, 'alg' => @@JWS_ALGORITHM, 'kid' => auth.public_key, @@JWS_HDR_URI => url, @@JWS_HDR_TIMESTAMP => Time.now.to_i * 1000, @@JWS_HDR_NONCE => SecureRandom.hex } hdr = urlsafe_encode64(jws_hdr.to_json) msg = hdr + '.' + urlsafe_encode64(props.map{|k,v| "#{k}=#{v}"}.join('&')) return msg + '.' + jws_sign(auth.private_key, msg) end |
.send_auth_request(props, context, auth) ⇒ Object
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
# File 'lib/simplify/paymentsapi.rb', line 255 def self.send_auth_request(props, context, auth) check_auth(auth) content_type = 'application/json' url = "#{Simplify::oauth_base_url}/#{context}" signature = oauth_jws_encode(auth, url, props) opts = { :method => 'POST', :payload => signature } user_agent = "Ruby-SDK/#{Constants::version}" if Simplify::user_agent != nil user_agent = "#{user_agent} #{Simplify::user_agent}" end opts = opts.merge({ :url => url, :headers => { 'Content-Type' => content_type, 'Accept' => 'application/json', 'User-Agent' => user_agent }.merge(opts[:headers] || {}) }) begin response = RestClient::Request.execute(opts) JSON.parse(response.body) rescue RestClient::Exception => e begin errorData = JSON.parse(e.response.body) rescue JSON::ParserError => e2 raise ApiException.new("Unknown error", nil, nil) end if e.response.code == @@HTTP_REDIRECTED raise BadRequestException.new("Unexpected response code returned from the API, have you got the correct URL?", e.response.code, {}) elsif e.response.code >= @@HTTP_BAD_REQUEST and e.response.code < @@HTTP_SERVER_ERROR error_code = errorData['error'] error_desc = errorData['error_description'] if (error_code == 'invalid_request') raise BadRequestException.new("", e.response.code, get_oauth_error("Error during OAuth request", error_code, error_desc)) elsif (error_code == 'access_denied') raise AuthenticationException.new("", e.response.code, get_oauth_error("Access denied for OAuth request", error_code, error_desc)) elsif (error_code == 'invalid_client') raise AuthenticationException.new("", e.response.code, get_oauth_error("Invalid client ID in OAuth request", error_code, error_desc)) elsif (error_code == 'unauthorized_client') raise AuthenticationException.new("", e.response.code, get_oauth_error("Unauthorized client in OAuth request", error_code, error_desc)) elsif (error_code == 'unsupported_grant_type') raise BadRequestException.new("", e.response.code, get_oauth_error("Unsupported grant type in OAuth request", error_code, error_desc)) elsif (error_code == 'invalid_scope') raise BadRequestException.new("", e.response.code, get_oauth_error("Invalid scope in OAuth request", error_code, error_desc)) else raise BadRequestException.new("", e.response.code, get_oauth_error("Unknown OAuth error", error_code, error_desc)) end else raise SystemException.new("An unexpected error has been raised. Looks like there's something wrong at our end.", e.response.code, nil) end end end |
.urlsafe_decode64(s) ⇒ Object
531 532 533 534 535 536 537 538 539 540 541 542 |
# File 'lib/simplify/paymentsapi.rb', line 531 def self.urlsafe_decode64(s) # Put back padding case (s.size % 4) when 0 when 2 s = s + "==" when 3 s = s + "=" else raise ArgumentError.new("Webhook event data incorrectly formatted", nil, nil) end return Base64::decode64(s.gsub('-','+').gsub('_','/')) end |
.urlsafe_encode64(s) ⇒ Object
Base64.urlsafe_encode64()/urlsafe_decode64() is not available in ruby 1.8
527 528 529 |
# File 'lib/simplify/paymentsapi.rb', line 527 def self.urlsafe_encode64(s) return Base64::encode64(s).gsub(/\n/, '').gsub('+', '-').gsub('/', '_').gsub('=', '') end |