amex_tokenization_client 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: bc1bed91ec19fe5de22c7ff1f400beb1194b3dedb786cdaf0b9d5508cec2517e
4
+ data.tar.gz: 1fda85c458678f521642fa5204bcab84a913b3f8a587bd27d29b0dccec06d2ea
5
+ SHA512:
6
+ metadata.gz: 7f3c8728670b59815678f7801dc7cbf3d0640bf223d16cbf102c577b36ff6a66ca8dada4acb052da1533224fd0fe33b068b109f70cd2bd1e231ce5754ffe3bcb
7
+ data.tar.gz: 53ea08d13c512d49a99f126bd588fbae6c77ddad17576000b02f28a997ecacc29f9d14940fa8d99051b4053d5bdf2c0d95f5d53eff4f1758d219fb3db8bd6711
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.4.5
7
+ before_install: gem install bundler -v 1.16.3
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in amex_tokenization_client.gemspec
6
+ gemspec
7
+
8
+ gem 'jwe', github: 'varyonic/ruby-jwe.git', branch: 'PR18' # Fix A256KW.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Piers Chambers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # AmexTokenizationClient
2
+
3
+ [![Travis CI Status](https://secure.travis-ci.org/varyonic/amex-api-ruby-client.svg)](https://travis-ci.org/varyonic/amex-api-ruby-client)
4
+
5
+ Unofficial Ruby wrapper for the American Express Tokenization Service (AETS).
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'amex_tokenization_client'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/varyonic/amex-api-ruby-client.
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,30 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "amex_tokenization_client/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "amex_tokenization_client"
8
+ spec.version = AmexTokenizationClient::VERSION
9
+ spec.authors = ["Piers Chambers"]
10
+ spec.email = ["piers@varyonic.com"]
11
+
12
+ spec.summary = "Unofficial Ruby wrapper for the American Express Tokenization Service (AETS)."
13
+ spec.homepage = "https://github.com/varyonic/amex-api-ruby-client"
14
+ spec.license = "MIT"
15
+
16
+ # Specify which files should be added to the gem when it is released.
17
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
18
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
19
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec)/}) }
20
+ end
21
+ spec.bindir = "exe"
22
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
23
+ spec.require_paths = ["lib"]
24
+
25
+ spec.add_dependency "jwe"
26
+
27
+ spec.add_development_dependency "bundler", "~> 1.16"
28
+ spec.add_development_dependency "rake", "~> 10.0"
29
+ spec.add_development_dependency "rspec", "~> 3.0"
30
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "amex_tokenization_client"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,16 @@
1
+ class AmexTokenizationClient
2
+ class NotificationsPayload
3
+ attr_reader :token_ref_id, :notification_type
4
+
5
+ def initialize(token_ref_id:, notification_type:)
6
+ @token_ref_id, @notification_type = token_ref_id, notification_type
7
+ end
8
+
9
+ def to_json(_encryption_key_id, _encryption_key)
10
+ Hash[
11
+ token_ref_id: token_ref_id,
12
+ notification_type: notification_type
13
+ ].to_json
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,41 @@
1
+ require 'json'
2
+
3
+ class AmexTokenizationClient
4
+ class ProvisioningPayload
5
+ attr_reader :account_number, :expiry_month, :expiry_year
6
+ attr_reader :name, :email, :is_on_file, :ip_address
7
+
8
+ def initialize(account_number:, name:, expiry_month:, expiry_year:, email:, is_on_file:, ip_address: nil)
9
+ @account_number, @expiry_month, @expiry_year = account_number, expiry_month, expiry_year
10
+ @name, @email, @is_on_file, @ip_address = name, email, is_on_file, ip_address
11
+ end
12
+
13
+ def to_json(encryption_key_id, encryption_key)
14
+ Hash[
15
+ account_data: account_data(encryption_key_id, encryption_key),
16
+ user_data: { name: name, email: email },
17
+ risk_assessment_data: risk_assessment_data
18
+ ].to_json
19
+ end
20
+
21
+ protected
22
+
23
+ def account_data(encryption_key_id, encryption_key)
24
+ json = JSON.generate Hash[
25
+ account_type: 'credit_card',
26
+ credit_card: { account_number: account_number, expiry_month: expiry_month, expiry_year: expiry_year }
27
+ ]
28
+ jwe_encrypt(json, encryption_key_id, encryption_key)
29
+ end
30
+
31
+ def risk_assessment_data
32
+ data = { account_input_method: is_on_file ? 'On File' : 'User Input' }
33
+ data[:ip_address] = ip_address if ip_address
34
+ data
35
+ end
36
+
37
+ def jwe_encrypt(data, encryption_key_id, encryption_key)
38
+ JWE.encrypt(data, encryption_key, alg: 'A256KW', enc: 'A128GCM', kid: encryption_key_id)
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,66 @@
1
+ require 'benchmark'
2
+ require 'net/http'
3
+
4
+ class AmexTokenizationClient
5
+ class Request
6
+ attr_reader :uri, :request
7
+ attr_reader :logger
8
+
9
+ def initialize(method, path, headers, logger:)
10
+ @logger = logger
11
+ @uri = URI(path)
12
+ @request = Net::HTTP.const_get(method.capitalize).new(uri)
13
+ headers.each_pair { |k, v| request[k] = v }
14
+ end
15
+
16
+ # Create HTTP request with provided headers.
17
+ # Invoke request over HTTPS.
18
+ # Return response on success or log failure and throw error.
19
+ def send(data = nil)
20
+ request.body = data if data
21
+ response = log_request_response(data) do
22
+ https(uri).request(request)
23
+ end
24
+ fail_unless_expected_response response, Net::HTTPSuccess
25
+ response.body
26
+ end
27
+
28
+ def https(uri)
29
+ Net::HTTP.new(uri.host, uri.port).tap do |http|
30
+ http.use_ssl = true
31
+ end
32
+ end
33
+
34
+ # Log URI, method, data
35
+ # Start timer.
36
+ # Yield URI, method, data.
37
+ # Log response and time taken.
38
+ def log_request_response(data = nil)
39
+ logger.info "[#{self.class.name}] request = #{request.method} #{uri}#{data ? '?' + data : ''}"
40
+ response = nil
41
+ tms = Benchmark.measure do
42
+ response = yield
43
+ end
44
+ logger.info("[#{self.class.name}] response (#{ms(tms)}ms): #{response.inspect} #{response.body}")
45
+ response
46
+ end
47
+
48
+ def ms(tms)
49
+ (tms.real*1000).round(3)
50
+ end
51
+
52
+ class UnexpectedHttpResponse < StandardError
53
+ def initialize(response)
54
+ super response.message || response.code
55
+ end
56
+ end
57
+
58
+ def fail_unless_expected_response(response, *allowed_responses)
59
+ unless allowed_responses.any? { |allowed| response.is_a?(allowed) }
60
+ logger.error "#{response.inspect}: #{response.body}"
61
+ raise UnexpectedHttpResponse, response
62
+ end
63
+ response
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,3 @@
1
+ class AmexTokenizationClient
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,97 @@
1
+ require 'base64'
2
+ require 'json'
3
+ require 'jwe'
4
+ require 'logger'
5
+ require 'openssl'
6
+ require "amex_tokenization_client/notifications_payload"
7
+ require "amex_tokenization_client/provisioning_payload"
8
+ require "amex_tokenization_client/request"
9
+ require "amex_tokenization_client/version"
10
+
11
+ class AmexTokenizationClient
12
+ attr_reader :host
13
+ attr_reader :base_path
14
+ attr_reader :token_requester_id
15
+ attr_reader :client_id, :client_secret
16
+ attr_reader :encryption_key_id, :encryption_key
17
+ attr_accessor :logger
18
+
19
+ def initialize(host:,
20
+ token_requester_id:,
21
+ client_id:, client_secret:,
22
+ encryption_key_id:, encryption_key:,
23
+ logger: Logger.new('/dev/null'))
24
+ @host = host
25
+ @base_path = "/payments/digital/v2/tokens".freeze
26
+ @token_requester_id = token_requester_id
27
+ @client_id, @client_secret = client_id, client_secret
28
+ @encryption_key_id, @encryption_key = encryption_key_id, Base64.decode64(encryption_key)
29
+ @logger = logger
30
+ end
31
+
32
+ # @return [Hash] token_ref_id and other values.
33
+ def provisioning(kargs)
34
+ response = JSON.parse send_authorized_request('POST', 'provisioning', provisioning_payload(kargs))
35
+ response.merge! JSON.parse jwe_decrypt response.delete('secure_token_data')
36
+ response
37
+ end
38
+
39
+ def notifications(kargs)
40
+ send_authorized_request('POST', 'notifications', notifications_payload(kargs))
41
+ end
42
+
43
+ def status(token_ref_id)
44
+ JSON.parse send_authorized_request('GET', "#{token_ref_id}/status")
45
+ end
46
+
47
+ def metadata(token_ref_id)
48
+ JSON.parse send_authorized_request('GET', "#{token_ref_id}/metadata")
49
+ end
50
+
51
+ def provisioning_payload(kargs)
52
+ ProvisioningPayload.new(kargs).to_json(encryption_key_id, encryption_key)
53
+ end
54
+
55
+ def notifications_payload(kargs)
56
+ NotificationsPayload.new(kargs).to_json(encryption_key_id, encryption_key)
57
+ end
58
+
59
+ def jwe_decrypt(data)
60
+ JWE.decrypt(data, encryption_key)
61
+ end
62
+
63
+ def send_authorized_request(method, route, payload = nil)
64
+ resource_path = "#{base_path}/#{route}"
65
+ authorization = hmac_authorization(method, resource_path, payload)
66
+ new_request(method, resource_path, authorization).send(payload)
67
+ end
68
+
69
+ # @param [String] method, e.g. 'POST'
70
+ # @param [String] resource_path, e.g. '/payments/digital/v2/tokens/provisioning'
71
+ # @param [String] JSON payload
72
+ # @return [String] Authorization: MAC id="gfFb4K8esqZgMpzwF9SXzKLCCbPYV8bR",ts="1463772177193",nonce="61129a8d-ca24-464b-8891-9251501d86f0", bodyhash="YJpz6NdGP0aV6aYaa+6qKCjQt46of+Cj4liBz90G6X8=", mac="uzybzLPj3fD8eBZaBzb4E7pZs+l+IWS0w/w2wwsExdo="
73
+ def hmac_authorization(method, resource_path, payload, nonce = SecureRandom.uuid, ts = (Time.now.to_r * 1000).to_i)
74
+ bodyhash = hmac_digest(payload)
75
+ mac = hmac_digest([ts, nonce, method, resource_path, host, 443, bodyhash, ''].join("\n"))
76
+ %(MAC id="#{client_id}",ts="#{ts}",nonce="#{nonce}",bodyhash="#{bodyhash}",mac="#{mac}")
77
+ end
78
+
79
+ def hmac_digest(s)
80
+ Base64.strict_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, client_secret, s.to_s))
81
+ end
82
+
83
+ def new_request(method, resource_path, authorization)
84
+ Request.new(method, "https://#{host}/#{resource_path}", headers(authorization), logger: logger)
85
+ end
86
+
87
+ def headers(authorization)
88
+ Hash[
89
+ 'Content-Type' => 'application/json',
90
+ 'Content-Language' => 'en-US',
91
+ 'x-amex-token-requester-id' => token_requester_id,
92
+ 'x-amex-api-key' => client_id,
93
+ 'x-amex-request-id' => SecureRandom.uuid,
94
+ 'authorization' => authorization,
95
+ ]
96
+ end
97
+ end
metadata ADDED
@@ -0,0 +1,115 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: amex_tokenization_client
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Piers Chambers
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-01-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: jwe
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.16'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.16'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ description:
70
+ email:
71
+ - piers@varyonic.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".rspec"
78
+ - ".travis.yml"
79
+ - Gemfile
80
+ - LICENSE.txt
81
+ - README.md
82
+ - Rakefile
83
+ - amex_tokenization_client.gemspec
84
+ - bin/console
85
+ - bin/setup
86
+ - lib/amex_tokenization_client.rb
87
+ - lib/amex_tokenization_client/notifications_payload.rb
88
+ - lib/amex_tokenization_client/provisioning_payload.rb
89
+ - lib/amex_tokenization_client/request.rb
90
+ - lib/amex_tokenization_client/version.rb
91
+ homepage: https://github.com/varyonic/amex-api-ruby-client
92
+ licenses:
93
+ - MIT
94
+ metadata: {}
95
+ post_install_message:
96
+ rdoc_options: []
97
+ require_paths:
98
+ - lib
99
+ required_ruby_version: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ required_rubygems_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ requirements: []
110
+ rubyforge_project:
111
+ rubygems_version: 2.7.7
112
+ signing_key:
113
+ specification_version: 4
114
+ summary: Unofficial Ruby wrapper for the American Express Tokenization Service (AETS).
115
+ test_files: []