afterpay-ruby 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1b138c6354737a0b52de2dea005597e8836b5fda092584a572b93953fb4954f5
4
+ data.tar.gz: fc7e8360debb62136e4048a84821ae6fd9833460ce84cc0b68a02181d30bf05d
5
+ SHA512:
6
+ metadata.gz: 9084a554247fa82cbe50b1653d099cdf2e2ba8a1b85a154e01a079e7c30d70ebf208dc83c72a12fde226e92bcabe0a3b2bef8e309eb2e70b96cc5638adf5ae88
7
+ data.tar.gz: 9f6e7b012de323610ef6895905fa3f574b23df743ca999e78d4bfdb5fec3d0cfbd6b9cd2db5895c5da1c78f07c7639d43663947a549556bd394a78cf134193e5
data/.env.sample ADDED
@@ -0,0 +1,2 @@
1
+ APP_ID=
2
+ SECRET=
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ .DS_Store
2
+ /.bundle/
3
+ /.yardoc
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
13
+ .env
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,31 @@
1
+ AllCops:
2
+ Exclude:
3
+ - "afterpay-ruby.gemspec"
4
+ - "bin/*"
5
+
6
+ Style/StringLiterals:
7
+ EnforcedStyle: double_quotes
8
+ Style/Documentation:
9
+ Enabled: false
10
+ Style/NumericLiterals:
11
+ Enabled: false
12
+ Style/FrozenStringLiteralComment:
13
+ EnforcedStyle: always
14
+ Exclude:
15
+ - "spec/**/*"
16
+ - "Gemfile"
17
+ - "Rakefile"
18
+
19
+ Metrics/BlockLength:
20
+ Exclude:
21
+ - "spec/**/*_spec.rb"
22
+ Metrics/LineLength:
23
+ Enabled: false
24
+ Metrics/AbcSize:
25
+ Enabled: false
26
+ Metrics/MethodLength:
27
+ Enabled: false
28
+
29
+ Naming/FileName:
30
+ Exclude:
31
+ - "lib/afterpay-ruby.rb"
data/.travis.yml ADDED
@@ -0,0 +1,10 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.2
7
+ - 2.6.1
8
+ - 2.5.1
9
+ - 2.3.3
10
+ before_install: gem install bundler -v 2.0.1
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at iamchoonggg@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in afterpay-ruby.gemspec
4
+ gemspec
5
+
6
+ group :test do
7
+ gem "simplecov", require: false
8
+ gem "vcr", "~> 4.0"
9
+ gem "webmock", "~> 3.5", ">= 3.5.1"
10
+ gem 'coveralls', require: false
11
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,89 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ afterpay-ruby (0.1.0)
5
+ faraday (>= 0.8, < 1.0)
6
+ faraday_middleware (~> 0.13.1)
7
+ money (>= 6.7.1, < 7.0.0)
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ addressable (2.6.0)
13
+ public_suffix (>= 2.0.2, < 4.0)
14
+ coderay (1.1.2)
15
+ concurrent-ruby (1.1.5)
16
+ coveralls (0.8.22)
17
+ json (>= 1.8, < 3)
18
+ simplecov (~> 0.16.1)
19
+ term-ansicolor (~> 1.3)
20
+ thor (~> 0.19.4)
21
+ tins (~> 1.6)
22
+ crack (0.4.3)
23
+ safe_yaml (~> 1.0.0)
24
+ diff-lcs (1.3)
25
+ docile (1.3.1)
26
+ dotenv (2.7.2)
27
+ faraday (0.15.4)
28
+ multipart-post (>= 1.2, < 3)
29
+ faraday_middleware (0.13.1)
30
+ faraday (>= 0.7.4, < 1.0)
31
+ hashdiff (0.3.8)
32
+ i18n (1.6.0)
33
+ concurrent-ruby (~> 1.0)
34
+ json (2.2.0)
35
+ method_source (0.9.2)
36
+ money (6.13.2)
37
+ i18n (>= 0.6.4, <= 2)
38
+ multipart-post (2.0.0)
39
+ pry (0.12.2)
40
+ coderay (~> 1.1.0)
41
+ method_source (~> 0.9.0)
42
+ public_suffix (3.0.3)
43
+ rake (10.5.0)
44
+ rspec (3.8.0)
45
+ rspec-core (~> 3.8.0)
46
+ rspec-expectations (~> 3.8.0)
47
+ rspec-mocks (~> 3.8.0)
48
+ rspec-core (3.8.0)
49
+ rspec-support (~> 3.8.0)
50
+ rspec-expectations (3.8.2)
51
+ diff-lcs (>= 1.2.0, < 2.0)
52
+ rspec-support (~> 3.8.0)
53
+ rspec-mocks (3.8.0)
54
+ diff-lcs (>= 1.2.0, < 2.0)
55
+ rspec-support (~> 3.8.0)
56
+ rspec-support (3.8.0)
57
+ safe_yaml (1.0.5)
58
+ simplecov (0.16.1)
59
+ docile (~> 1.1)
60
+ json (>= 1.8, < 3)
61
+ simplecov-html (~> 0.10.0)
62
+ simplecov-html (0.10.2)
63
+ term-ansicolor (1.7.1)
64
+ tins (~> 1.0)
65
+ thor (0.19.4)
66
+ tins (1.20.2)
67
+ vcr (4.0.0)
68
+ webmock (3.5.1)
69
+ addressable (>= 2.3.6)
70
+ crack (>= 0.3.2)
71
+ hashdiff
72
+
73
+ PLATFORMS
74
+ ruby
75
+
76
+ DEPENDENCIES
77
+ afterpay-ruby!
78
+ bundler (~> 2.0)
79
+ coveralls
80
+ dotenv (~> 2.2, >= 2.2.1)
81
+ pry
82
+ rake (~> 10.0)
83
+ rspec (~> 3.0)
84
+ simplecov
85
+ vcr (~> 4.0)
86
+ webmock (~> 3.5, >= 3.5.1)
87
+
88
+ BUNDLED WITH
89
+ 2.0.1
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Elijah Goh Chong Hui
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,111 @@
1
+ [![Build Status](https://travis-ci.org/bluethumbart/afterpay-ruby.svg?branch=master)](https://travis-ci.org/bluethumbart/afterpay-ruby)
2
+ [![Coverage Status](https://coveralls.io/repos/github/bluethumbart/afterpay-ruby/badge.svg?branch=master)](https://coveralls.io/github/bluethumbart/afterpay-ruby?branch=master)
3
+
4
+ # Afterpay Ruby
5
+
6
+ Based on the [API docs](https://docs.afterpay.com/au-online-api-v1.html)
7
+
8
+ Afterpay Ruby is a Ruby wrapper for Afterpay API. It provides simple DSL and serialization to Afterpay's API attribute.
9
+
10
+ ## Installation
11
+
12
+ Add this line to your application's Gemfile:
13
+
14
+ ```ruby
15
+ gem 'afterpay-ruby'
16
+ ```
17
+
18
+ And then execute:
19
+
20
+ $ bundle
21
+
22
+ Or install it yourself as:
23
+
24
+ $ gem install afterpay-ruby
25
+
26
+ ## Usage
27
+
28
+ You need to configure Afterpay using your Merchant ID and secret.
29
+
30
+ For Rails, put this in your initializer.
31
+
32
+ ```ruby
33
+ Afterpay.configure do |config|
34
+ config.app_id = <app_id>
35
+ config.secret = <secret>
36
+
37
+ # Sets the environment for Afterpay
38
+ # defaults to sandbox
39
+ # config.env = "sandbox" # "live"
40
+ end
41
+ ```
42
+
43
+ ### Creating an Order - [api docs](https://docs.afterpay.com/au-online-api-v1.html#create-order)
44
+
45
+ ```ruby
46
+ order = Afterpay::Order.create(
47
+ total: <Money>,
48
+ consumer: <Afterpay::Consumer>,
49
+ items: [<Afterpay::Item>],
50
+ success_url: <String>,
51
+ cancel_url: <String>
52
+ )
53
+
54
+ # OR
55
+
56
+ order = Afterpay::Order.new(
57
+ ...
58
+ )
59
+ order.create
60
+
61
+
62
+ order.success?
63
+ => true
64
+ order.token
65
+ => xxxxxxx
66
+
67
+ # Error
68
+
69
+ order.success?
70
+ => false
71
+ order.error
72
+ => Afterpay::Error:0x00007f8a63953888
73
+ @id="48da0bce49d39625",
74
+ @code="invalid_object",
75
+ @message="merchant.redirectConfirmUrl must be a valid URL, merchant.redirectConfirmUrl may not be empty" >
76
+ ```
77
+
78
+ ### Executing Payment
79
+
80
+ ```ruby
81
+ payment = Afterpay::Payment.execute(
82
+ token: token <String>,
83
+ reference: "checkout-1" <String>
84
+ )
85
+ => <Afterpay::Payment ...>
86
+
87
+ payment.success?
88
+ => true
89
+ payment.order
90
+ => <Afterpay::Order ...>
91
+ payment.status
92
+ => APPROVED
93
+ ```
94
+
95
+ ## Development
96
+
97
+ 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.
98
+
99
+ 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).
100
+
101
+ ## Contributing
102
+
103
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/afterpay-ruby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
104
+
105
+ ## License
106
+
107
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
108
+
109
+ ## Code of Conduct
110
+
111
+ Everyone interacting in the Afterpay::Ruby project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/afterpay-ruby/blob/master/CODE_OF_CONDUCT.md).
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,45 @@
1
+ lib = File.expand_path("../lib", __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require "afterpay/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "afterpay-ruby"
7
+ spec.version = Afterpay::VERSION
8
+ spec.authors = ["Eli"]
9
+ spec.email = ["chonghui@bluethumb.com.au"]
10
+
11
+ spec.summary = "Afterpay ruby wrapper"
12
+ spec.homepage = "https://github.com/bluethumbart/afterpay-ruby"
13
+ spec.license = "MIT"
14
+
15
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
16
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
17
+ if spec.respond_to?(:metadata)
18
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
19
+
20
+ spec.metadata["homepage_uri"] = spec.homepage
21
+ spec.metadata["source_code_uri"] = "https://github.com/bluethumbart/afterpay-ruby"
22
+ else
23
+ raise "RubyGems 2.0 or newer is required to protect against " \
24
+ "public gem pushes."
25
+ end
26
+
27
+ # Specify which files should be added to the gem when it is released.
28
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
29
+ spec.files = Dir.chdir(File.expand_path("..", __FILE__)) do
30
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
31
+ end
32
+ spec.bindir = "exe"
33
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
34
+ spec.require_paths = ["lib"]
35
+
36
+ spec.add_development_dependency "bundler", "~> 2.0"
37
+ spec.add_development_dependency "rake", "~> 10.0"
38
+ spec.add_development_dependency "rspec", "~> 3.0"
39
+ spec.add_development_dependency "dotenv", "~> 2.2", ">= 2.2.1"
40
+ spec.add_development_dependency "pry"
41
+
42
+ spec.add_dependency "faraday", ">= 0.8", "< 1.0"
43
+ spec.add_dependency "faraday_middleware", "~> 0.13.1"
44
+ spec.add_dependency "money", ">= 6.7.1", "< 7.0.0"
45
+ end
data/bin/bundle ADDED
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ #
5
+ # This file was generated by Bundler.
6
+ #
7
+ # The application 'bundle' is installed as part of a gem, and
8
+ # this file is here to facilitate running it.
9
+ #
10
+
11
+ require "rubygems"
12
+
13
+ m = Module.new do
14
+ module_function
15
+
16
+ def invoked_as_script?
17
+ File.expand_path($PROGRAM_NAME) == File.expand_path(__FILE__)
18
+ end
19
+
20
+ def env_var_version
21
+ ENV["BUNDLER_VERSION"]
22
+ end
23
+
24
+ def cli_arg_version
25
+ return unless invoked_as_script? # don't want to hijack other binstubs
26
+ return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update`
27
+
28
+ bundler_version = nil
29
+ update_index = nil
30
+ ARGV.each_with_index do |a, i|
31
+ bundler_version = a if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
32
+ next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/
33
+
34
+ bundler_version = Regexp.last_match(1) || ">= 0.a"
35
+ update_index = i
36
+ end
37
+ bundler_version
38
+ end
39
+
40
+ def gemfile
41
+ gemfile = ENV["BUNDLE_GEMFILE"]
42
+ return gemfile if gemfile && !gemfile.empty?
43
+
44
+ File.expand_path("../Gemfile", __dir__)
45
+ end
46
+
47
+ def lockfile
48
+ lockfile =
49
+ case File.basename(gemfile)
50
+ when "gems.rb" then gemfile.sub(/\.rb$/, gemfile)
51
+ else "#{gemfile}.lock"
52
+ end
53
+ File.expand_path(lockfile)
54
+ end
55
+
56
+ def lockfile_version
57
+ return unless File.file?(lockfile)
58
+
59
+ lockfile_contents = File.read(lockfile)
60
+ return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/
61
+
62
+ Regexp.last_match(1)
63
+ end
64
+
65
+ def bundler_version
66
+ @bundler_version ||= begin
67
+ env_var_version || cli_arg_version ||
68
+ lockfile_version || "#{Gem::Requirement.default}.a"
69
+ end
70
+ end
71
+
72
+ def load_bundler!
73
+ ENV["BUNDLE_GEMFILE"] ||= gemfile
74
+
75
+ # must dup string for RG < 1.8 compatibility
76
+ activate_bundler(bundler_version.dup)
77
+ end
78
+
79
+ def activate_bundler(bundler_version)
80
+ bundler_version = "< 2" if Gem::Version.correct?(bundler_version) && Gem::Version.new(bundler_version).release < Gem::Version.new("2.0")
81
+ gem_error = activation_error_handling do
82
+ gem "bundler", bundler_version
83
+ end
84
+ return if gem_error.nil?
85
+
86
+ require_error = activation_error_handling do
87
+ require "bundler/version"
88
+ end
89
+ return if require_error.nil? && Gem::Requirement.new(bundler_version).satisfied_by?(Gem::Version.new(Bundler::VERSION))
90
+
91
+ warn "Activating bundler (#{bundler_version}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_version}'`"
92
+ exit 42
93
+ end
94
+
95
+ def activation_error_handling
96
+ yield
97
+ nil
98
+ rescue StandardError, LoadError => e
99
+ e
100
+ end
101
+ end
102
+
103
+ m.load_bundler!
104
+
105
+ load Gem.bin_path("bundler", "bundle") if m.invoked_as_script?
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler"
4
+ require "bundler/setup"
5
+ require "afterpay"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ 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
data/configure.rb ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dotenv"
4
+ Dotenv.load
5
+
6
+ Afterpay.configure do |config|
7
+ config.app_id = ENV["APP_ID"]
8
+ config.secret = ENV["SECRET"]
9
+
10
+ # Sets to raise errors when 404
11
+ # config.raise_errors = true
12
+
13
+ # Sets the environment for Afterpay
14
+ # config.env = "sandbox" # :live
15
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "faraday"
4
+ require "faraday_middleware"
5
+ require "base64"
6
+ require "forwardable"
7
+
8
+ module Afterpay
9
+ # Client object acting as the connection
10
+ # Enables the Client to call get/post/patch/delete
11
+ class Client
12
+ extend Forwardable
13
+
14
+ BASE_URL = "https://api.afterpay.com/".freeze
15
+ SANDBOX_BASE_URL = "https://api-sandbox.afterpay.com/".freeze
16
+
17
+ class NotFoundError < StandardError; end
18
+ class UnauthorizedError < StandardError; end
19
+
20
+ def_delegators :@connection, :get, :put, :post, :delete
21
+
22
+ # Decides which URL to use based on env
23
+ def self.server_url
24
+ Afterpay.env == "sandbox" ? SANDBOX_BASE_URL : BASE_URL
25
+ end
26
+
27
+ # Auth requires format to be Base64 encoded
28
+ # `<app_id>:<secret>`
29
+ def self.auth_token
30
+ auth_str = "#{Afterpay.config.app_id}:#{Afterpay.config.secret}"
31
+
32
+ Base64.strict_encode64(auth_str)
33
+ end
34
+
35
+ def initialize(connection = nil)
36
+ @connection = connection || default_connection
37
+ end
38
+
39
+ # The connection object
40
+ def default_connection
41
+ # Use local thread to keep connection open to make use of connection reuse.
42
+ Thread.current[:afterpay_default_connection] ||=
43
+ Faraday.new(url: self.class.server_url) do |conn|
44
+ conn.use ErrorMiddleware if Afterpay.config.raise_errors
45
+ conn.authorization "Basic", self.class.auth_token
46
+
47
+ conn.request :json
48
+ conn.response :json, content_type: "application/json", parser_options: { symbolize_names: true }
49
+ conn.adapter Faraday.default_adapter
50
+ end
51
+ end
52
+ end
53
+
54
+ # Error middleware for Faraday to raise Afterpay connection errors
55
+ class ErrorMiddleware
56
+ def initialize(app)
57
+ @app = app
58
+ end
59
+
60
+ def call(env)
61
+ @app.call(env).on_complete do
62
+ case env[:status]
63
+ when 404
64
+ raise Client::NotFoundError, env.dig(:body, "message")
65
+ when 401
66
+ raise Client::UnauthorizedError, env.dig(:body, "message")
67
+ end
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Afterpay
4
+ class Config
5
+ attr_accessor :app_id, :secret, :env, :raise_errors,
6
+ :type, :maximum_amount, :minimum_amount,
7
+ :description, :currency
8
+
9
+ def initialize
10
+ @env = "sandbox"
11
+ @raise_errors = true
12
+ end
13
+
14
+ # Called only after app_id and secred is set
15
+ def fetch_remote_config
16
+ response = Afterpay.client.get("/v1/configuration").body[0]
17
+
18
+ @type = response[:type]
19
+ @minimum_amount = response.dig(:minimumAmount, :amount).to_f
20
+ @maximum_amount = response.dig(:maximumAmount, :amount).to_f
21
+ @description = response[:description]
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Afterpay
4
+ class Consumer
5
+ attr_accessor :email, :phone, :first_name, :last_name
6
+
7
+ def initialize(email:, phone:, first_name:, last_name:)
8
+ @email = email
9
+ @phone = phone
10
+ @first_name = first_name
11
+ @last_name = last_name
12
+ end
13
+
14
+ def to_hash
15
+ {
16
+ phoneNumber: phone,
17
+ givenNames: first_name,
18
+ surname: last_name,
19
+ email: email
20
+ }
21
+ end
22
+
23
+ # Builds Consumer from response
24
+ def self.from_response(response)
25
+ return nil if response.nil?
26
+
27
+ new(
28
+ email: response[:email],
29
+ first_name: response[:givenNames],
30
+ last_name: response[:surname],
31
+ phone: response[:phoneNumber]
32
+ )
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Afterpay
4
+ # Error class with accessor to methods
5
+ # Afterpay error returns the same format containing
6
+ # `errorId`, `errorCode`, `message`
7
+ class Error
8
+ attr_accessor :code, :id, :message
9
+
10
+ def initialize(response)
11
+ @id = response[:errorId]
12
+ @code = response[:errorCode]
13
+ @message = response[:message]
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "money"
4
+
5
+ module Afterpay
6
+ class Item
7
+ attr_accessor :name, :sku, :quantity, :price
8
+
9
+ def initialize(name:, sku:, price:, quantity: 1)
10
+ @name = name
11
+ @sku = sku
12
+ @quantity = quantity
13
+ @price = price
14
+ end
15
+
16
+ def to_hash
17
+ {
18
+ name: name,
19
+ sku: sku,
20
+ quantity: quantity,
21
+ price: {
22
+ amount: price.to_f,
23
+ currency: price.currency
24
+ }
25
+ }
26
+ end
27
+
28
+ # Builds Item from response
29
+ def self.from_response(response)
30
+ return nil if response.nil?
31
+
32
+ new(
33
+ name: response[:name],
34
+ sku: response[:sku],
35
+ quantity: response[:quantity],
36
+ price: MoneyUtil.from_response(response[:price])
37
+ )
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Afterpay
4
+ # Money utility
5
+ module MoneyUtil
6
+ # Converts Afterpay response to `Money`
7
+ # @return [Money]
8
+ def self.from_response(response)
9
+ return nil if response.nil?
10
+
11
+ Money.from_amount(
12
+ response[:amount].to_f,
13
+ response[:currency]
14
+ )
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ostruct"
4
+ require "forwardable"
5
+
6
+ module Afterpay
7
+ # The Order object for creating an order to `/v1/orders`
8
+ class Order
9
+ extend Forwardable
10
+
11
+ def_delegators :@attributes,
12
+ :total,
13
+ :consumer,
14
+ :items,
15
+ :shipping,
16
+ :tax,
17
+ :discounts,
18
+ :billing,
19
+ :shipping,
20
+ :merchant_reference
21
+
22
+ # Finds Order from Afterpay API
23
+ # @param token [String]
24
+ # @return [Order]
25
+ def self.find(token)
26
+ request = Afterpay.client.get("/v1/orders/#{token}")
27
+
28
+ Order.from_response(request.body)
29
+ end
30
+
31
+ # Builds Order from response
32
+ # @param response [Hash] response params from API
33
+ # @return [Order]
34
+ def self.from_response(response)
35
+ return nil if response.nil?
36
+
37
+ new(
38
+ total: MoneyUtil.from_response(response[:total]),
39
+ consumer: Consumer.from_response(response[:consumer]),
40
+ items: response[:items].map { |item| Item.from_response(item) },
41
+ # billing: response[:billing],
42
+ # shipping: response[:shipping],
43
+ # discounts: Discount.from_response(response[:discounts]),
44
+ tax: MoneyUtil.from_response(response[:taxAmount]),
45
+ shipping: MoneyUtil.from_response(response[:shippingAmount])
46
+ )
47
+ end
48
+
49
+ # Helper function to create an Order and calls #create
50
+ #
51
+ # @param (see #initialize)
52
+ # @return [Order::Response] containing token, error, valid?
53
+ def self.create(*args)
54
+ new(*args).create
55
+ end
56
+
57
+ attr_reader :attributes, :expiry, :token, :error
58
+
59
+ # Initializes an Order object
60
+ #
61
+ # @overload initialize(total:, items:, consumer:, success_url:, cancel_url:, payment_type:)
62
+ # @param total [Money] a Money object
63
+ # @param items [Array<Afterpay::Item>] receives items for order
64
+ # @param consumer [Afterpay::Consume] the consumer for the order
65
+ # @param success_url [String] the path to redirect on successful payment
66
+ # @param cancel_url [String] the path to redirect on failed payment
67
+ # @param payment_type [String] Payment type defaults to {Config#type}
68
+ def initialize(attributes = {})
69
+ @attributes = OpenStruct.new(attributes)
70
+ @attributes.payment_type ||= Afterpay.config.type
71
+ @token = @attributes.token || nil
72
+ @expiry = nil
73
+ @error = nil
74
+ end
75
+
76
+ # Builds structure to API specs
77
+ def to_hash
78
+ {
79
+ totalAmount: {
80
+ amount: total.to_f,
81
+ currency: total.currency.iso_code
82
+ },
83
+ consumer: consumer.to_hash,
84
+ items: items.map(&:to_hash),
85
+ merchant: {
86
+ redirectConfirmUrl: attributes.success_url,
87
+ redirectCancelUrl: attributes.cancel_url
88
+ },
89
+ merchantReference: attributes.merchant_reference,
90
+ taxAmount: attributes.tax,
91
+ shippingAmount: attributes.shipping,
92
+ paymentType: attributes.payment_type
93
+ }
94
+ end
95
+
96
+ # Sends the create request to Afterpay server
97
+ # @return [Response]
98
+ def create
99
+ request = Afterpay.client.post("/v1/orders") do |req|
100
+ req.body = to_hash
101
+ end
102
+ response = request.body
103
+
104
+ if request.success?
105
+ @expiry = Time.parse(response[:expires])
106
+ @token = response[:token]
107
+ else
108
+ @error = Error.new(response)
109
+ end
110
+ end
111
+
112
+ def success?
113
+ !@token.nil?
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Afterpay
4
+ # They Payment object
5
+ class Payment
6
+ # Executes the Payment
7
+ #
8
+ # @param token [String] the Order token
9
+ # @param reference [String] the reference for payment
10
+ # @return [Payment] the Payment object
11
+ def self.execute(token:, reference:)
12
+ request = Afterpay.client.post("/v1/payments/capture") do |req|
13
+ req.body = {
14
+ token: token,
15
+ merchantRefernce: reference
16
+ }
17
+ end
18
+
19
+ new(request.body)
20
+ end
21
+
22
+ attr_accessor :id, :status, :created, :total, :order, :error
23
+
24
+ # Initialize Payment from response
25
+ def initialize(attributes)
26
+ @id = attributes[:id]
27
+ @status = attributes[:status]
28
+ @created = attributes[:created]
29
+ @total = MoneyUtil.from_response(attributes[:total])
30
+ @order = Order.from_response(attributes[:orderDetails])
31
+ @error = Error.new(attributes) if attributes[:errorId]
32
+ end
33
+
34
+ def success?
35
+ @status == "APPROVED"
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Afterpay
4
+ VERSION = "0.1.0".freeze
5
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Bundler naming convention
4
+ # This gem is called afterpay_ruby
5
+ # thus bundler will require afterpay_ruby
6
+ require "afterpay"
data/lib/afterpay.rb ADDED
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "money"
4
+ require_relative "afterpay/version"
5
+ require_relative "afterpay/client"
6
+ require_relative "afterpay/config"
7
+ require_relative "afterpay/consumer"
8
+ require_relative "afterpay/item"
9
+ require_relative "afterpay/order"
10
+ require_relative "afterpay/payment"
11
+ require_relative "afterpay/error"
12
+ require_relative "afterpay/money_util"
13
+
14
+ module Afterpay
15
+ class << self
16
+ attr_accessor :config
17
+ end
18
+
19
+ # Helper function for Afterpay::Client
20
+ # Use Afterpay.client to send receive request
21
+ def self.client
22
+ Client.new
23
+ end
24
+
25
+ # Configure block to setup configuration
26
+ #
27
+ # Afterpay.configure do |conf|
28
+ # conf.app_id = <app_id>
29
+ # conf.secret = <secret>
30
+ # end
31
+ #
32
+ def self.configure
33
+ self.config ||= Config.new
34
+ yield(config) if block_given?
35
+ config.fetch_remote_config
36
+ config.freeze if config.env == "live"
37
+ end
38
+
39
+ def self.env
40
+ config.env
41
+ end
42
+ end
metadata ADDED
@@ -0,0 +1,203 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: afterpay-ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Eli
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-04-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: dotenv
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.2'
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: 2.2.1
65
+ type: :development
66
+ prerelease: false
67
+ version_requirements: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - "~>"
70
+ - !ruby/object:Gem::Version
71
+ version: '2.2'
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: 2.2.1
75
+ - !ruby/object:Gem::Dependency
76
+ name: pry
77
+ requirement: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ type: :development
83
+ prerelease: false
84
+ version_requirements: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ - !ruby/object:Gem::Dependency
90
+ name: faraday
91
+ requirement: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0.8'
96
+ - - "<"
97
+ - !ruby/object:Gem::Version
98
+ version: '1.0'
99
+ type: :runtime
100
+ prerelease: false
101
+ version_requirements: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '0.8'
106
+ - - "<"
107
+ - !ruby/object:Gem::Version
108
+ version: '1.0'
109
+ - !ruby/object:Gem::Dependency
110
+ name: faraday_middleware
111
+ requirement: !ruby/object:Gem::Requirement
112
+ requirements:
113
+ - - "~>"
114
+ - !ruby/object:Gem::Version
115
+ version: 0.13.1
116
+ type: :runtime
117
+ prerelease: false
118
+ version_requirements: !ruby/object:Gem::Requirement
119
+ requirements:
120
+ - - "~>"
121
+ - !ruby/object:Gem::Version
122
+ version: 0.13.1
123
+ - !ruby/object:Gem::Dependency
124
+ name: money
125
+ requirement: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - ">="
128
+ - !ruby/object:Gem::Version
129
+ version: 6.7.1
130
+ - - "<"
131
+ - !ruby/object:Gem::Version
132
+ version: 7.0.0
133
+ type: :runtime
134
+ prerelease: false
135
+ version_requirements: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - ">="
138
+ - !ruby/object:Gem::Version
139
+ version: 6.7.1
140
+ - - "<"
141
+ - !ruby/object:Gem::Version
142
+ version: 7.0.0
143
+ description:
144
+ email:
145
+ - chonghui@bluethumb.com.au
146
+ executables: []
147
+ extensions: []
148
+ extra_rdoc_files: []
149
+ files:
150
+ - ".env.sample"
151
+ - ".gitignore"
152
+ - ".rspec"
153
+ - ".rubocop.yml"
154
+ - ".travis.yml"
155
+ - CODE_OF_CONDUCT.md
156
+ - Gemfile
157
+ - Gemfile.lock
158
+ - LICENSE.txt
159
+ - README.md
160
+ - Rakefile
161
+ - afterpay-ruby.gemspec
162
+ - bin/bundle
163
+ - bin/console
164
+ - bin/setup
165
+ - configure.rb
166
+ - lib/afterpay-ruby.rb
167
+ - lib/afterpay.rb
168
+ - lib/afterpay/client.rb
169
+ - lib/afterpay/config.rb
170
+ - lib/afterpay/consumer.rb
171
+ - lib/afterpay/error.rb
172
+ - lib/afterpay/item.rb
173
+ - lib/afterpay/money_util.rb
174
+ - lib/afterpay/order.rb
175
+ - lib/afterpay/payment.rb
176
+ - lib/afterpay/version.rb
177
+ homepage: https://github.com/bluethumbart/afterpay-ruby
178
+ licenses:
179
+ - MIT
180
+ metadata:
181
+ allowed_push_host: https://rubygems.org
182
+ homepage_uri: https://github.com/bluethumbart/afterpay-ruby
183
+ source_code_uri: https://github.com/bluethumbart/afterpay-ruby
184
+ post_install_message:
185
+ rdoc_options: []
186
+ require_paths:
187
+ - lib
188
+ required_ruby_version: !ruby/object:Gem::Requirement
189
+ requirements:
190
+ - - ">="
191
+ - !ruby/object:Gem::Version
192
+ version: '0'
193
+ required_rubygems_version: !ruby/object:Gem::Requirement
194
+ requirements:
195
+ - - ">="
196
+ - !ruby/object:Gem::Version
197
+ version: '0'
198
+ requirements: []
199
+ rubygems_version: 3.0.1
200
+ signing_key:
201
+ specification_version: 4
202
+ summary: Afterpay ruby wrapper
203
+ test_files: []