paystack-gateway 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: b006328b301fcf8623f6112708bfcc417a3ac526e624b5808fe734b4363f12b5
4
+ data.tar.gz: 52b87e2c79a821070b5dd7f742fde3eb73e2f164ea1d9163f8ad9c007299f580
5
+ SHA512:
6
+ metadata.gz: 1678a9c29c4bcda5ed2440c70979efa7bf3171549baf07f6b086ec0a2bcf309b12ce9a367c324649958dffc1f6e705fb396616db4b67b026eddaf986ad2a5220
7
+ data.tar.gz: 1b9fd60c1f84978915cf365e551176f4a93fb63274a675430ead26d3b37bfdd9f36f900f6a4ef8966b44189995353edcd9d5286c863c59487a7b66e4db0b2d8a
data/.rubocop.yml ADDED
@@ -0,0 +1,25 @@
1
+ require:
2
+ - rubocop-minitest
3
+ - rubocop-rake
4
+
5
+ AllCops:
6
+ TargetRubyVersion: 3.3
7
+ NewCops: enable
8
+
9
+ Metrics/AbcSize:
10
+ Max: 25
11
+ Metrics/MethodLength:
12
+ Max: 25
13
+ Minitest/MultipleAssertions:
14
+ Enabled: false
15
+ Naming/FileName:
16
+ Exclude:
17
+ - lib/paystack-gateway.rb
18
+ Style/NegatedIf:
19
+ Enabled: false
20
+ Style/TrailingCommaInArrayLiteral:
21
+ EnforcedStyleForMultiline: consistent_comma
22
+ Style/TrailingCommaInHashLiteral:
23
+ EnforcedStyleForMultiline: consistent_comma
24
+ Style/TrailingCommaInArguments:
25
+ EnforcedStyleForMultiline: consistent_comma
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-10-27
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 darthrighteous
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,206 @@
1
+ # PaystackGateway
2
+
3
+ `paystack-gateway` is a Ruby library that provides easy-to-use bindings for the [Paystack API](https://paystack.com/docs/api/). This library provides a collection of modules, methods and helpers for interacting with Paystack's API endpoints. It includes built-in error handling, caching, parsing, and logging.
4
+
5
+ ## Installation
6
+ Install the gem and add to the application's Gemfile by executing:
7
+
8
+ ```bash
9
+ $ bundle add PLACEHOLDER_GEM_NAME
10
+ ```
11
+
12
+ If bundler is not being used to manage dependencies, install the gem by executing:
13
+
14
+ ```bash
15
+ $ gem install PLACEHOLDER_GEM_NAME
16
+ ```
17
+
18
+ ## Configuration
19
+
20
+ To use the PaystackGateway gem, you need to configure it with your Paystack secret key. You can do this in an initializer or directly in your application code.
21
+
22
+ The configuration options are
23
+ - `secret_key`: Your paystack api key used to authorize requests
24
+ - `logger`: Your ruby Logger. Default is Logger.new($stdout)
25
+ - `logging_options`: Options passed to [Faraday logger middleware](https://github.com/lostisland/faraday/blob/main/lib/faraday/response/logger.rb). Default is `{ headers: false }`
26
+ - `log_filter`: Filter used when logging headers and body.
27
+
28
+ ```ruby
29
+ # config/initializers/paystack_gateway.rb
30
+
31
+ PaystackGateway.configure do |config|
32
+ config.secret_key = Rails.application.credentials.dig(:paystack, :secret_key)
33
+ config.logger = Rails.logger
34
+ config.log_filter = ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters).method(:filter)
35
+ end
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ### Calling API endpoints
41
+ Once configured, you can start using the various API modules and methods provided by the gem. They are designed to mirror how the api methods are grouped and listed on the [Paystack API](https://paystack.com/docs/api/).
42
+
43
+ Here's an example creating a customer using the [/customer/create endpoint](https://paystack.com/docs/api/customer/#create).
44
+
45
+ ```ruby
46
+ response = PaystackGateway::Customers.create_customer(
47
+ email: 'test@example.com',
48
+ first_name: 'Test',
49
+ last_name: 'User',
50
+ )
51
+
52
+ response.id # => 203316808
53
+ response.customer_code # => "CUS_xsrozmbt8g1oear"
54
+ ```
55
+
56
+ ### Error Handling
57
+ Whenever a network error occurs or the called endpoint responds with an error response, a `PaystackGateway::ApiError`(or a subclass of it) is raised that can be handled in your calling code.
58
+
59
+ Here's an example initializing a transaction using the [/transaction/initialize endpoint](https://paystack.com/docs/api/transaction/#initialize)
60
+
61
+ ```ruby
62
+ begin
63
+ response = PaystackGateway::Transactions.initialize_transaction(
64
+ email: 'test@example.com',
65
+ amount: 1000,
66
+ reference: 'test_reference',
67
+ )
68
+ return response.payment_url
69
+
70
+ rescue InitializeTransactionError => e # subclass of PaystackGateway::ApiError
71
+ cancel_payment if e.cancellable?
72
+
73
+ rescue PaystackGateway::ApiError => e
74
+ handle_initialize_error(e)
75
+ end
76
+ ```
77
+
78
+ ### Caching
79
+
80
+ While caching is implemented in the library, it is currently not configurable for all modules and api methods. With a little more work, this can be achieved. So if there's demand for it, I can work on it (PRs are also welcome 🙂).
81
+
82
+ Some endpoints currently make use of caching:
83
+ - Miscellaneous#list_banks
84
+ - Verifications#resolve_account_number
85
+
86
+ Caching works using an [ActiveSupport::Cache::FileStore](https://api.rubyonrails.org/classes/ActiveSupport/Cache/FileStore.html) cache. The default caching period is 7 days and the cache data is stored on the file system at `ENV['TMPDIR']` or `/tmp/cache`.
87
+
88
+
89
+ ## API Modules and Methods
90
+ > Refer to the [Paystack API documentation](https://paystack.com/docs/api) for details on all the available endpoints and their usage.
91
+
92
+ ### Implemented Modules and Methods
93
+
94
+ Below is a complete list of the API modules and methods that are currently implemented.
95
+
96
+ I invite you to collaborate on this project! If you need to use any of the unimplemented API methods or modules, or if you want to make modifications to the defaults or the level of configuration available in the currently implemented API methods, please feel free to raise a pull request (PR). See [Contributing](#contributing) and [Code of Conduct](#code-of-conduct) below
97
+
98
+ - [x] [Transactions](https://paystack.com/docs/api/transaction/)
99
+ - [x] [Initialize Transaction](https://paystack.com/docs/api/transaction/#initialize)
100
+ - [x] [Verify Transaction](https://paystack.com/docs/api/transaction/#verify)
101
+ - [ ] [List Transactions](https://paystack.com/docs/api/transaction/#list)
102
+ - [ ] [Fetch Transaction](https://paystack.com/docs/api/transaction/#fetch)
103
+ - [x] [Charge Authorization](https://paystack.com/docs/api/transaction/#charge-authorization)
104
+ - [ ] [View Transaction Timeline](https://paystack.com/docs/api/transaction/#view-timeline)
105
+ - [ ] [Transaction Totals](https://paystack.com/docs/api/transaction/#totals)
106
+ - [ ] [Export Transactions](https://paystack.com/docs/api/transaction/#export)
107
+ - [ ] [Partial Debit](https://paystack.com/docs/api/transaction/#partial-debit)
108
+
109
+ - [ ] [Customers](https://paystack.com/docs/api/customer/)
110
+ - [x] [Create Customer](https://paystack.com/docs/api/customer/#create)
111
+ - [ ] [List Customers](https://paystack.com/docs/api/customer/#list)
112
+ - [x] [Fetch Customer](https://paystack.com/docs/api/customer/#fetch)
113
+ - [ ] [Update Customer](https://paystack.com/docs/api/customer/#update)
114
+ - [ ] [Validate Customer](https://paystack.com/docs/api/customer/#validate)
115
+ - [ ] [Whitelist/Blacklist Customer](https://paystack.com/docs/api/customer/#whitelist-blacklist)
116
+ - [ ] [Deactivate Authorization](https://paystack.com/docs/api/customer/#deactivate-authorization)
117
+
118
+ - [x] [Dedicated Virtual Accounts](https://paystack.com/docs/api/dedicated-virtual-account/)
119
+ - [x] [Create Dedicated Virtual Account](https://paystack.com/docs/api/dedicated-virtual-account/#create)
120
+ - [x] [Assign Dedicated Virtual Account](https://paystack.com/docs/api/dedicated-virtual-account/#assign)
121
+ - [ ] [List Dedicated Accounts](https://paystack.com/docs/api/dedicated-virtual-account/#list)
122
+ - [ ] [Fetch Dedicated Account](https://paystack.com/docs/api/dedicated-virtual-account/#fetch)
123
+ - [x] [Requery Dedicated Account](https://paystack.com/docs/api/dedicated-virtual-account/#requery)
124
+ - [ ] [Deactivate Dedicated Account](https://paystack.com/docs/api/dedicated-virtual-account/#deactivate)
125
+ - [x] [Split Dedicated Account Transaction](https://paystack.com/docs/api/dedicated-virtual-account/#add-split)
126
+ - [ ] [Remove Split from Dedicated Account](https://paystack.com/docs/api/dedicated-virtual-account/#remove-split)
127
+ - [ ] [Fetch Bank Providers](https://paystack.com/docs/api/dedicated-virtual-account/#providers)
128
+
129
+ - [ ] [Subaccounts](https://paystack.com/docs/api/subaccount/)
130
+ - [x] [Create Subaccount](https://paystack.com/docs/api/subaccount/#create)
131
+ - [ ] [List Subaccounts](https://paystack.com/docs/api/subaccount/#list)
132
+ - [ ] [Fetch Subaccount](https://paystack.com/docs/api/subaccount/#fetch)
133
+ - [x] [Update Subaccount](https://paystack.com/docs/api/subaccount/#update)
134
+
135
+ - [x] [Plans](https://paystack.com/docs/api/plan/)
136
+ - [x] [Create Plan](https://paystack.com/docs/api/plan/#create)
137
+ - [x] [List Plans](https://paystack.com/docs/api/plan/#list)
138
+ - [x] [Fetch Plan](https://paystack.com/docs/api/plan/#fetch)
139
+ - [x] [Update Plan](https://paystack.com/docs/api/plan/#update)
140
+
141
+ - [x] [Transfer Recipients](https://paystack.com/docs/api/transfer-recipient/)
142
+ - [x] [Create Transfer Recipient](https://paystack.com/docs/api/transfer-recipient/#create)
143
+ - [ ] [Bulk Create Transfer Recipient](https://paystack.com/docs/api/transfer-recipient/#bulk)
144
+ - [ ] [List Transfer Recipients](https://paystack.com/docs/api/transfer-recipient/#list)
145
+ - [ ] [Fetch Transfer Recipient](https://paystack.com/docs/api/transfer-recipient/#fetch)
146
+ - [ ] [Update Transfer Recipient](https://paystack.com/docs/api/transfer-recipient/#update)
147
+ - [ ] [Delete Transfer Recipient](https://paystack.com/docs/api/transfer-recipient/#delete)
148
+
149
+ - [x] [Transfers](https://paystack.com/docs/api/transfer/)
150
+ - [x] [Initiate Transfer](https://paystack.com/docs/api/transfer/#initiate)
151
+ - [ ] [Finalize Transfer](https://paystack.com/docs/api/transfer/#finalize)
152
+ - [ ] [Initiate Bulk Transfer](https://paystack.com/docs/api/transfer/#bulk)
153
+ - [ ] [List Transfers](https://paystack.com/docs/api/transfer/#list)
154
+ - [ ] [Fetch Transfer](https://paystack.com/docs/api/transfer/#fetch)
155
+ - [x] [Verify Transfer](https://paystack.com/docs/api/transfer/#verify)
156
+
157
+ - [x] [Refunds](https://paystack.com/docs/api/refund/)
158
+ - [x] [Create Refund](https://paystack.com/docs/api/refund/#create)
159
+ - [x] [List Refunds](https://paystack.com/docs/api/refund/#list)
160
+ - [x] [Fetch Refund](https://paystack.com/docs/api/refund/#fetch)
161
+
162
+ - [x] [Verification](https://paystack.com/docs/api/verification/)
163
+ - [x] [Resolve Account Number](https://paystack.com/docs/api/verification/#resolve-account)
164
+ - [ ] [Validate Account](https://paystack.com/docs/api/verification/#validate-account)
165
+ - [ ] [Resolve Card BIN](https://paystack.com/docs/api/verification/#resolve-card)
166
+
167
+ - [x] [Miscellaneous](https://paystack.com/docs/api/miscellaneous/)
168
+ - [x] [List Banks](https://paystack.com/docs/api/miscellaneous/#bank)
169
+ - [ ] [List/Search Countries](https://paystack.com/docs/api/miscellaneous/#country)
170
+ - [ ] [List States (AVS)](https://paystack.com/docs/api/miscellaneous/#avs-states)
171
+
172
+
173
+ ## Development
174
+
175
+ 1. Fork the repository.
176
+ 2. Create a new branch for your feature or bugfix.
177
+ 3. Make your changes, add tests for them.
178
+ 4. Ensure the tests and linter pass
179
+ 5. Open a pull request with a detailed description of your changes.
180
+
181
+ ### Setting up
182
+
183
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
184
+
185
+ ### Running the tests and linter
186
+
187
+ Minitest is used for unit tests. Rubocop is used to enforce the ruby style.
188
+
189
+ To run the complete set of tests and linter run the following:
190
+
191
+ ```bash
192
+ $ bundle install
193
+ $ bundle exec rake test
194
+ $ bundle exec rubocop
195
+ ```
196
+
197
+ ## Contributing
198
+
199
+ Bug reports and pull requests are welcome on GitHub at https://github.com/darthrighteous/paystack-gateway. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[darthrighteous/paystackgateway/blob/master/CODE_OF_CONDUCT.md).
200
+
201
+ ## License
202
+
203
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
204
+
205
+ ## Code of Conduct
206
+ Everyone interacting in the PaystackGateway project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[darthrighteous/paystackgateway/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'minitest/test_task'
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Faraday
4
+ class Response
5
+ # https://github.com/lostisland/faraday_middleware/blob/main/lib/faraday_middleware/response/caching.rb
6
+ class Caching < Middleware
7
+ attr_reader :cache
8
+
9
+ # Internal: List of status codes that can be cached:
10
+ # * 200 - 'OK'
11
+ # * 203 - 'Non-Authoritative Information'
12
+ # * 300 - 'Multiple Choices'
13
+ # * 301 - 'Moved Permanently'
14
+ # * 302 - 'Found'
15
+ # * 404 - 'Not Found'
16
+ # * 410 - 'Gone'
17
+ CACHEABLE_STATUS_CODES = [200, 203, 300, 301, 302, 404, 410].freeze
18
+
19
+ extend Forwardable
20
+ def_delegators :'Faraday::Utils', :parse_query, :build_query
21
+
22
+ # Public: initialize the middleware.
23
+ #
24
+ # cache - An object that responds to read and write (default: nil).
25
+ # options - An options Hash (default: {}):
26
+ # :ignore_params - String name or Array names of query
27
+ # params that should be ignored when forming
28
+ # the cache key (default: []).
29
+ # :write_options - Hash of settings that should be passed as the
30
+ # third options parameter to the cache's #write
31
+ # method. If not specified, no options parameter
32
+ # will be passed.
33
+ # :full_key - Boolean - use full URL as cache key:
34
+ # (url.host + url.request_uri)
35
+ # :status_codes - Array of http status code to be cache
36
+ # (default: CACHEABLE_STATUS_CODE)
37
+ #
38
+ # Yields if no cache is given. The block should return a cache object.
39
+ def initialize(app, cache = nil, options = {})
40
+ super(app)
41
+ if cache.is_a?(Hash) && block_given?
42
+ options = cache
43
+ cache = nil
44
+ end
45
+ @cache = cache || yield
46
+ @options = options
47
+ end
48
+
49
+ def call(env)
50
+ if env[:method] == :get
51
+ if env[:parallel_manager]
52
+ # callback mode
53
+ cache_on_complete(env)
54
+ else
55
+ # synchronous mode
56
+ key = cache_key(env)
57
+ unless (response = cache.read(key)) && response
58
+ response = @app.call(env)
59
+ store_response_in_cache(key, response)
60
+ end
61
+ finalize_response(response, env)
62
+ end
63
+ else
64
+ @app.call(env)
65
+ end
66
+ end
67
+
68
+ def cache_key(env)
69
+ url = env[:url].dup
70
+ if url.query && params_to_ignore.any?
71
+ params = parse_query url.query
72
+ params.reject! { |k,| params_to_ignore.include? k }
73
+ url.query = params.any? ? build_query(params) : nil
74
+ end
75
+ url.normalize!
76
+ digest = full_key? ? url.host + url.request_uri : url.request_uri
77
+ Digest::SHA1.hexdigest(digest)
78
+ end
79
+
80
+ def params_to_ignore
81
+ @params_to_ignore ||= Array(@options[:ignore_params]).map(&:to_s)
82
+ end
83
+
84
+ def full_key?
85
+ @full_key ||= @options[:full_key]
86
+ end
87
+
88
+ def custom_status_codes
89
+ @custom_status_codes ||= begin
90
+ codes = CACHEABLE_STATUS_CODES & Array(@options[:status_codes]).map(&:to_i)
91
+ codes.any? ? codes : CACHEABLE_STATUS_CODES
92
+ end
93
+ end
94
+
95
+ def cache_on_complete(env)
96
+ key = cache_key(env)
97
+ if (cached_response = cache.read(key))
98
+ finalize_response(cached_response, env)
99
+ else
100
+ # response.status is nil at this point
101
+ # any checks need to be done inside on_complete block
102
+ @app.call(env).on_complete do |response_env|
103
+ store_response_in_cache(key, response_env.response)
104
+ response_env
105
+ end
106
+ end
107
+ end
108
+
109
+ def store_response_in_cache(key, response)
110
+ return unless custom_status_codes.include?(response.status)
111
+
112
+ if @options[:write_options]
113
+ cache.write(key, response, @options[:write_options])
114
+ else
115
+ cache.write(key, response)
116
+ end
117
+ end
118
+
119
+ def finalize_response(response, env)
120
+ response = response.dup if response.frozen?
121
+ env[:response] = response
122
+ unless env[:response_headers]
123
+ env.update response.env
124
+ # FIXME: omg hax
125
+ response.instance_variable_set('@env', env)
126
+ end
127
+ response
128
+ end
129
+ end
130
+ end
131
+ end
132
+
133
+ Faraday::Response.register_middleware(caching: Faraday::Response::Caching)
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Faraday
4
+ class Response
5
+ # Parse response bodies as Hashie::Mash.
6
+ class Mashify < Middleware
7
+ def initialize(app = nil, mash_class: Hashie::Mash, symbolize: true)
8
+ super(app)
9
+
10
+ @mash_class = mash_class
11
+ @symbolize = symbolize
12
+ end
13
+
14
+ def on_complete(env)
15
+ process_response(env)
16
+ end
17
+
18
+ private
19
+
20
+ def process_response(env)
21
+ env[:body] = env[:body].try(:deep_symbolize_keys) if @symbolize
22
+ env[:body] = parse(env[:body])
23
+ rescue StandardError, SyntaxError => e
24
+ raise Faraday::ParsingError.new(e, env[:response])
25
+ end
26
+
27
+ def parse(body)
28
+ case body
29
+ when Hash
30
+ @mash_class.new(body)
31
+ when Array
32
+ body.map { |item| parse(item) }
33
+ else
34
+ body
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
40
+
41
+ Faraday::Response.register_middleware(mashify: Faraday::Response::Mashify)
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'paystack_gateway'
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'faraday/error'
4
+
5
+ module PaystackGateway
6
+ # This error is raised when an exception occurs in the process of fulfilling
7
+ # an api method.
8
+ #
9
+ # It allows for dynamic checking of the error message by calling a method.
10
+ # * Calling `error.foo_error?` will return true if the error message is
11
+ # "foo_error" or "foo".
12
+ #
13
+ # * Calling `error.foo_error!` ensures that subsequent calls to
14
+ # `error.foo_error?` return true regardless of the message.
15
+ #
16
+ # api_method def initialize_transaction(**transaction_data)
17
+ # raise ApiError.new(:invalid_amount, cancellable: true) if !transaction_data[:amount]
18
+ # ...
19
+ # end
20
+ #
21
+ # begin
22
+ # initialize_transaction({amount: nil})
23
+ # rescue ApiError => e
24
+ # handle_invalid_amount_error(e) if e.invalid_amount_error? # => true
25
+ # cancel_transaction if e.cancellable?
26
+ # end
27
+ class ApiError < StandardError
28
+ CONNECTION_ERROR_CLASSES = [
29
+ Faraday::ServerError,
30
+ Faraday::ConnectionFailed,
31
+ Faraday::SSLError,
32
+ ].freeze
33
+
34
+ attr_reader :original_error, :cancellable
35
+ alias cancellable? cancellable
36
+
37
+ def initialize(msg = nil, original_error: nil, cancellable: false)
38
+ super(msg)
39
+
40
+ @original_error = original_error
41
+ @cancellable = cancellable
42
+ end
43
+
44
+ def network_error? = original_error&.class&.in?(CONNECTION_ERROR_CLASSES)
45
+
46
+ def method_missing(method_name, *)
47
+ return super unless method_name.to_s.end_with?('_error?', '_error!')
48
+
49
+ if method_name.to_s.end_with?('_error!')
50
+ define_singleton_method(method_name.to_s.sub(/!$/, '?')) { true }
51
+ elsif method_name.to_s.end_with?('_error?')
52
+ matching_messages = [
53
+ method_name.to_s.remove(/_error\?$/),
54
+ method_name.to_s.remove(/\?$/),
55
+ ]
56
+ message.to_s.in?(matching_messages)
57
+ end
58
+ end
59
+
60
+ def respond_to_missing?(method_name, *)
61
+ method_name.to_s.end_with?('_error?', '_error!') || super
62
+ end
63
+
64
+ private
65
+
66
+ def http_code = original_error.try(:response_status)
67
+ def response_body = original_error.try(:response_body)&.with_indifferent_access
68
+ end
69
+ end