MVola 0.1.0.pre.alpha
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 +7 -0
- data/.idea/workspace.xml +525 -0
- data/.overcommit.yml +20 -0
- data/.rspec +3 -0
- data/.standard.yml +3 -0
- data/CHANGELOG.md +6 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +78 -0
- data/Rakefile +10 -0
- data/lib/mvola/client/token.rb +22 -0
- data/lib/mvola/client.rb +113 -0
- data/lib/mvola/errors.rb +9 -0
- data/lib/mvola/request.rb +80 -0
- data/lib/mvola/transaction/payment_status.rb +48 -0
- data/lib/mvola/transaction.rb +105 -0
- data/lib/mvola/version.rb +5 -0
- data/lib/mvola.rb +20 -0
- data/sig/lib/mvola/client/token.rbs +21 -0
- data/sig/lib/mvola/client.rbs +56 -0
- data/sig/lib/mvola/request.rbs +13 -0
- data/sig/lib/mvola/transaction/payment_status.rbs +46 -0
- data/sig/mvola.rbs +5 -0
- metadata +65 -0
data/CODE_OF_CONDUCT.md
ADDED
@@ -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 Kassam
|
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,78 @@
|
|
1
|
+
# MVola
|
2
|
+
|
3
|
+

|
4
|
+
|
5
|
+
MVola is a Ruby gem that provides a simple way to interact with the [Mvola Payment API](https://mvola.mg/).
|
6
|
+
|
7
|
+
## Installation
|
8
|
+
|
9
|
+
Install the gem and add to the application's Gemfile by executing:
|
10
|
+
|
11
|
+
```bash
|
12
|
+
bundle add mvola
|
13
|
+
```
|
14
|
+
|
15
|
+
If bundler is not being used to manage dependencies, install the gem by executing:
|
16
|
+
|
17
|
+
```bash
|
18
|
+
gem install mvola
|
19
|
+
```
|
20
|
+
|
21
|
+
## Usage
|
22
|
+
|
23
|
+
before using the gem, ensure you have the credentials required to interact with the Mvola API (**Consumer Key** and **Consumer Secret**).
|
24
|
+
|
25
|
+
### Get Access Token
|
26
|
+
|
27
|
+
To get an access token, use the `MVola::Client` class and call the `token`
|
28
|
+
|
29
|
+
```ruby
|
30
|
+
client = MVola::Client.new(consumer_key: 'your_consumer_key', consumer_secret: 'your_consumer_secret')
|
31
|
+
# For sandbox environment, pass the sandbox option as true
|
32
|
+
# client = MVola::Client.new(consumer_key: 'your_consumer_key', consumer_secret: 'your_consumer_secret', sandbox: true)
|
33
|
+
|
34
|
+
client.token # <MVola::Client::Token access_token="your_access_token", token_type="Bearer", expires_at=2024-12-30 16:19:42 +0100, scope="EXT_INT_MVOLA_SCOPE">
|
35
|
+
```
|
36
|
+
|
37
|
+
The `token` method store the data at instance level, so that we when called multiple times, we don't have to request a new token each time, until the token expires.
|
38
|
+
If you want to force a new token, you can use the method:
|
39
|
+
```ruby
|
40
|
+
client.token!
|
41
|
+
```
|
42
|
+
|
43
|
+
#### Tips
|
44
|
+
|
45
|
+
We suggest that you store the token in cache system (like `Redis`) and passes the value directly into the client to avoid requesting a new token each time, across multiple instances of the application:
|
46
|
+
```ruby
|
47
|
+
token = client.token
|
48
|
+
# Store the value in cache
|
49
|
+
cache.write('mvola_token', token.to_h)
|
50
|
+
|
51
|
+
# then next time, you can use the value from cache
|
52
|
+
token = cache.read('mvola_token')
|
53
|
+
client = MVola::Client.new(consumer_key: 'your_consumer_key', consumer_secret: 'your_consumer_secret', token: token)
|
54
|
+
|
55
|
+
client.token # will use the provided token if it's still valid/not expired
|
56
|
+
```
|
57
|
+
|
58
|
+
## Development
|
59
|
+
|
60
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests.
|
61
|
+
You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
62
|
+
|
63
|
+
To install this gem onto your local machine, run `bundle exec rake install`.
|
64
|
+
|
65
|
+
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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
66
|
+
|
67
|
+
## Contributing
|
68
|
+
|
69
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/Ksm125/MVola.
|
70
|
+
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/Ksm125/MVola/blob/main/CODE_OF_CONDUCT.md).
|
71
|
+
|
72
|
+
## License
|
73
|
+
|
74
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
75
|
+
|
76
|
+
## Code of Conduct
|
77
|
+
|
78
|
+
Everyone interacting in the MVola project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/MVola/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
@@ -0,0 +1,22 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module MVola
|
4
|
+
class Client
|
5
|
+
Token = Struct.new(:access_token, :scope, :token_type, :expires_at, keyword_init: true) do
|
6
|
+
def expired?
|
7
|
+
Time.now >= expires_at - expires_margin
|
8
|
+
end
|
9
|
+
|
10
|
+
def valid?
|
11
|
+
!expired?
|
12
|
+
end
|
13
|
+
|
14
|
+
private
|
15
|
+
|
16
|
+
# Add a margin to the expiration time to avoid using an expired token.
|
17
|
+
def expires_margin
|
18
|
+
5 * 60 # 5 minutes
|
19
|
+
end
|
20
|
+
end
|
21
|
+
end
|
22
|
+
end
|
data/lib/mvola/client.rb
ADDED
@@ -0,0 +1,113 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "client/token"
|
4
|
+
require_relative "request"
|
5
|
+
|
6
|
+
module MVola
|
7
|
+
class Client
|
8
|
+
include Request
|
9
|
+
|
10
|
+
SANDBOX_URL = "https://devapi.mvola.mg"
|
11
|
+
PRODUCTION_URL = "https://api.mvola.mg"
|
12
|
+
SANDBOX_PARTNER_PHONE_NUMBER = "0343500003"
|
13
|
+
|
14
|
+
USER_LANGUAGES = {
|
15
|
+
fr: "FR",
|
16
|
+
mg: "MG"
|
17
|
+
}.freeze
|
18
|
+
|
19
|
+
attr_reader :consumer_key, :consumer_secret, :partner_name, :partner_phone_number, :user_language, :sandbox
|
20
|
+
alias_method :sandbox?, :sandbox
|
21
|
+
|
22
|
+
# @param consumer_key [String] the consumer key provided by MVola for the application
|
23
|
+
# @param consumer_secret [String] the consumer secret provided by MVola for the application
|
24
|
+
# @param partner_name [String] the name of the partner account
|
25
|
+
# @param partner_phone_number [String] the phone number of the partner account.
|
26
|
+
# This is replaced by a default value in the sandbox environment
|
27
|
+
# @param sandbox [Boolean] whether to use the sandbox environment or not.
|
28
|
+
# @param token [Hash, Token] a previous stored token to use for the client.
|
29
|
+
# If provided and that it is still valid, it will be used instead of fetching a new one.
|
30
|
+
def initialize(consumer_key: ENV["MVOLA_CONSUMER_KEY"],
|
31
|
+
consumer_secret: ENV["MVOLA_CONSUMER_SECRET"],
|
32
|
+
partner_name: ENV["MVOLA_PARTNER_NAME"],
|
33
|
+
partner_phone_number: ENV["MVOLA_PARTNER_PHONE_NUMBER"],
|
34
|
+
sandbox: false,
|
35
|
+
user_language: USER_LANGUAGES[:fr],
|
36
|
+
token: nil)
|
37
|
+
raise ArgumentError, "consumer_key is required" unless consumer_key
|
38
|
+
raise ArgumentError, "consumer_secret is required" unless consumer_secret
|
39
|
+
raise ArgumentError, "partner_name is required" unless partner_name
|
40
|
+
|
41
|
+
partner_phone_number = SANDBOX_PARTNER_PHONE_NUMBER if sandbox
|
42
|
+
raise ArgumentError, "partner_phone_number is required" unless partner_phone_number
|
43
|
+
|
44
|
+
# Warn invalid user language if not one of the supported languages
|
45
|
+
unless USER_LANGUAGES.key?(user_language.downcase.to_sym)
|
46
|
+
logger.warn "Invalid user language: #{user_language}. Using default language: #{USER_LANGUAGES[:fr]}"
|
47
|
+
end
|
48
|
+
|
49
|
+
@consumer_key = consumer_key
|
50
|
+
@consumer_secret = consumer_secret
|
51
|
+
@partner_name = partner_name
|
52
|
+
@partner_phone_number = partner_phone_number
|
53
|
+
@sandbox = sandbox
|
54
|
+
@token = build_token_from(token)
|
55
|
+
@user_language = USER_LANGUAGES.fetch(user_language.downcase.to_sym, USER_LANGUAGES[:fr])
|
56
|
+
@mutex = Mutex.new
|
57
|
+
end
|
58
|
+
|
59
|
+
# Get the token. If the token is not valid, it will be refreshed.
|
60
|
+
def token
|
61
|
+
return @token if @token&.valid?
|
62
|
+
|
63
|
+
@mutex.synchronize do
|
64
|
+
@token = build_token_from(fetch_token)
|
65
|
+
end
|
66
|
+
end
|
67
|
+
|
68
|
+
# Force the token to be refreshed, even if it is still valid.
|
69
|
+
def token!
|
70
|
+
@token = nil
|
71
|
+
token
|
72
|
+
end
|
73
|
+
|
74
|
+
# This method is used to determine the base URL for the API requests.
|
75
|
+
def base_url
|
76
|
+
sandbox? ? SANDBOX_URL : PRODUCTION_URL
|
77
|
+
end
|
78
|
+
|
79
|
+
private
|
80
|
+
|
81
|
+
# This method is used to build a token object from a hash or a token object.
|
82
|
+
def build_token_from(data)
|
83
|
+
return data if data.is_a?(Token)
|
84
|
+
return unless data.is_a?(Hash)
|
85
|
+
|
86
|
+
hash = data.dup
|
87
|
+
hash[:expires_at] ||= Time.now + hash.delete(:expires_in).to_i
|
88
|
+
hash[:expires_at] = Time.parse(hash[:expires_at].to_s) if hash[:expires_at].is_a?(String)
|
89
|
+
Token.new(**hash)
|
90
|
+
end
|
91
|
+
|
92
|
+
def headers
|
93
|
+
{
|
94
|
+
"Authorization" => "Basic #{Base64.strict_encode64("#{consumer_key}:#{consumer_secret}")}",
|
95
|
+
"Content-Type" => "application/x-www-form-urlencoded",
|
96
|
+
"Cache-Control" => "no-cache"
|
97
|
+
}
|
98
|
+
end
|
99
|
+
|
100
|
+
# Perform a request to fetch a new token from the MVola API.
|
101
|
+
def fetch_token
|
102
|
+
url = URI.join(base_url, "token").to_s
|
103
|
+
body = {
|
104
|
+
grant_type: "client_credentials",
|
105
|
+
scope: "EXT_INT_MVOLA_SCOPE"
|
106
|
+
}
|
107
|
+
|
108
|
+
response = post(url, headers: headers, body: body)
|
109
|
+
|
110
|
+
JSON.parse(response.body, symbolize_names: true)
|
111
|
+
end
|
112
|
+
end
|
113
|
+
end
|
data/lib/mvola/errors.rb
ADDED
@@ -0,0 +1,80 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "net/http"
|
4
|
+
require "forwardable"
|
5
|
+
|
6
|
+
module MVola
|
7
|
+
module Request
|
8
|
+
extend Forwardable
|
9
|
+
|
10
|
+
def_delegators MVola, :logger
|
11
|
+
|
12
|
+
# Method to perform a GET request
|
13
|
+
# @param url [String] the URL to perform the request
|
14
|
+
# @param args [Hash] the arguments to pass to the request
|
15
|
+
# @option args [Hash] :params the parameters to pass to the request
|
16
|
+
# @option args [Hash] :headers the headers to pass to the request
|
17
|
+
def get(url, args = {})
|
18
|
+
uri = URI.parse(url)
|
19
|
+
headers = args.delete(:headers) || {}
|
20
|
+
request = Net::HTTP::Get.new(uri.request_uri, headers)
|
21
|
+
|
22
|
+
logger.debug("GET #{url} #{args}")
|
23
|
+
response = build_http(uri, args).request(request)
|
24
|
+
logger.debug("Response: #{response.code} #{response.body.inspect}")
|
25
|
+
|
26
|
+
handle_error(response)
|
27
|
+
|
28
|
+
response
|
29
|
+
end
|
30
|
+
|
31
|
+
# Method to perform a POST request
|
32
|
+
# @param url [String] the URL to perform the request
|
33
|
+
# @param args [Hash] the arguments to pass to the request
|
34
|
+
# @option args [Hash] :params the parameters to pass to the request
|
35
|
+
# @option args [Hash] :headers the headers to pass to the request
|
36
|
+
# @option args [Hash] :body the body to pass to the request
|
37
|
+
# @option args [Hash] :json the JSON to pass to the request body. Replace the body if present
|
38
|
+
def post(url, args = {})
|
39
|
+
uri = URI.parse(url)
|
40
|
+
headers = args.delete(:headers) || {}
|
41
|
+
headers["Content-Type"] = "application/json" if args.key?(:json)
|
42
|
+
|
43
|
+
request = Net::HTTP::Post.new(uri.request_uri, headers)
|
44
|
+
|
45
|
+
request.form_data = args[:body] if args[:body]
|
46
|
+
if (json = args.delete(:json))
|
47
|
+
request.body = json.to_json
|
48
|
+
end
|
49
|
+
|
50
|
+
puts("POST #{url} #{args}")
|
51
|
+
response = build_http(uri, args).request(request)
|
52
|
+
puts("Response: #{response.code} #{response.body.inspect}")
|
53
|
+
|
54
|
+
handle_error(response)
|
55
|
+
|
56
|
+
response
|
57
|
+
end
|
58
|
+
|
59
|
+
private
|
60
|
+
|
61
|
+
def build_http(uri, args)
|
62
|
+
uri.query = URI.encode_www_form(args[:params]) if args[:params]
|
63
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
64
|
+
http.use_ssl = true
|
65
|
+
|
66
|
+
http
|
67
|
+
end
|
68
|
+
|
69
|
+
def handle_error(response)
|
70
|
+
case response.code.to_i
|
71
|
+
when 200..299
|
72
|
+
# Do nothing
|
73
|
+
when 401
|
74
|
+
raise MVola::Unauthorized, response.body
|
75
|
+
else
|
76
|
+
raise MVola::InvalidRequest, "Code: #{response.code}, Body: #{response.body}"
|
77
|
+
end
|
78
|
+
end
|
79
|
+
end
|
80
|
+
end
|
@@ -0,0 +1,48 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module MVola
|
4
|
+
class Transaction
|
5
|
+
# PaymentStatus is a class that represents the status of a payment.
|
6
|
+
# It is used as return value of the initiate_payment! and status of a transaction.
|
7
|
+
# This is aimed to be used internally, and not exposed to the public API.
|
8
|
+
class PaymentStatus
|
9
|
+
extend Forwardable
|
10
|
+
|
11
|
+
attr_reader :raw_response, :client_correlation_id
|
12
|
+
|
13
|
+
# raw_response is a hash data returned from the API
|
14
|
+
def initialize(raw_response, client_correlation_id:)
|
15
|
+
@raw_response = raw_response
|
16
|
+
@client_correlation_id = client_correlation_id
|
17
|
+
end
|
18
|
+
|
19
|
+
def status
|
20
|
+
raw_response["status"]
|
21
|
+
end
|
22
|
+
|
23
|
+
def server_correlation_id
|
24
|
+
raw_response["serverCorrelationId"]
|
25
|
+
end
|
26
|
+
|
27
|
+
def notification_method
|
28
|
+
raw_response["notificationMethod"]
|
29
|
+
end
|
30
|
+
|
31
|
+
def transaction_reference
|
32
|
+
raw_response["objectReference"]
|
33
|
+
end
|
34
|
+
|
35
|
+
def pending?
|
36
|
+
status == "pending"
|
37
|
+
end
|
38
|
+
|
39
|
+
def completed?
|
40
|
+
status == "completed"
|
41
|
+
end
|
42
|
+
|
43
|
+
def failed?
|
44
|
+
status == "failed"
|
45
|
+
end
|
46
|
+
end
|
47
|
+
end
|
48
|
+
end
|
@@ -0,0 +1,105 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "client"
|
4
|
+
require_relative "transaction/payment_status"
|
5
|
+
|
6
|
+
module MVola
|
7
|
+
class Transaction
|
8
|
+
include Request
|
9
|
+
|
10
|
+
API_VERSION = "1.0.0"
|
11
|
+
ENDPOINT = "mvola/mm/transactions/type/merchantpay/#{API_VERSION}"
|
12
|
+
CURRENCY = "Ar"
|
13
|
+
|
14
|
+
attr_reader :client
|
15
|
+
|
16
|
+
def initialize(client: nil)
|
17
|
+
@client = client || Client.new
|
18
|
+
end
|
19
|
+
|
20
|
+
# Initiate a payment from a debit phone number to a credit phone number.
|
21
|
+
# @param [Number | String] amount the amount to transfer
|
22
|
+
# @param [String] debit_phone_number the phone number to debit
|
23
|
+
# @param [String] credit_phone_number the phone number to credit
|
24
|
+
# @param [String] transaction_reference the transaction reference
|
25
|
+
# @param [String] original_transaction_reference the original transaction reference.
|
26
|
+
# Defaults to the `transaction_reference` if not provided
|
27
|
+
# @param [String] client_correlation_id the client correlation ID. Defaults to a random UUID
|
28
|
+
# @param [String] description the description of the payment
|
29
|
+
# @param [String] callback_url the callback URL to use for the payment
|
30
|
+
# @param [Array<Hash>] metadata additional metadata to use for the payment.
|
31
|
+
# Eg: [{ key: "fc", value: "USD" }, { key: "amountFc", value: "1" }]
|
32
|
+
def initiate_payment!(amount:,
|
33
|
+
debit_phone_number:,
|
34
|
+
credit_phone_number:,
|
35
|
+
transaction_reference:,
|
36
|
+
original_transaction_reference: transaction_reference,
|
37
|
+
client_correlation_id: SecureRandom.uuid,
|
38
|
+
description: nil,
|
39
|
+
callback_url: nil,
|
40
|
+
metadata: [])
|
41
|
+
payload = {
|
42
|
+
amount: amount.to_s,
|
43
|
+
currency: CURRENCY,
|
44
|
+
descriptionText: description,
|
45
|
+
requestDate: Time.now.strftime("%Y-%m-%dT%H:%M:%S.%LZ"),
|
46
|
+
requestingOrganisationTransactionReference: transaction_reference,
|
47
|
+
originalTransactionReference: original_transaction_reference,
|
48
|
+
debitParty: [{key: "msisdn", value: debit_phone_number}],
|
49
|
+
creditParty: [{key: "msisdn", value: credit_phone_number}],
|
50
|
+
metadata: [{key: "partnerName", value: client.partner_name}, *metadata]
|
51
|
+
}
|
52
|
+
headers = build_headers(client_correlation_id: client_correlation_id, callback_url: callback_url)
|
53
|
+
logger.info "Initiating payment with payload: #{payload}"
|
54
|
+
response = post(url_for, json: payload, headers: headers)
|
55
|
+
logger.info "Payment initiated. Response: #{response.body}"
|
56
|
+
|
57
|
+
parsed_body = JSON.parse(response.body)
|
58
|
+
PaymentStatus.new(parsed_body, client_correlation_id: client_correlation_id)
|
59
|
+
end
|
60
|
+
|
61
|
+
# Get the status of a payment using the server correlation ID.
|
62
|
+
# This can be used to poll the status of a payment.
|
63
|
+
def get_status(server_correlation_id, client_correlation_id: SecureRandom.uuid)
|
64
|
+
url = url_for("status/#{server_correlation_id}")
|
65
|
+
|
66
|
+
headers = build_headers(client_correlation_id: client_correlation_id)
|
67
|
+
response = get(url, headers: headers)
|
68
|
+
|
69
|
+
parsed_body = JSON.parse(response.body)
|
70
|
+
PaymentStatus.new(parsed_body, client_correlation_id: client_correlation_id)
|
71
|
+
end
|
72
|
+
|
73
|
+
# Get the details of a transaction using the transaction ID returned from the API.
|
74
|
+
def get_details(transaction_id, client_correlation_id: SecureRandom.uuid)
|
75
|
+
url = url_for(transaction_id)
|
76
|
+
|
77
|
+
headers = build_headers(client_correlation_id: client_correlation_id)
|
78
|
+
get url, headers: headers
|
79
|
+
end
|
80
|
+
|
81
|
+
private
|
82
|
+
|
83
|
+
# Generate the URL for the given path by joining the base URL and the endpoint.
|
84
|
+
def url_for(path = "")
|
85
|
+
safe_path = path.gsub(/^\//, "") # Remove starting slash from the path (if any) to avoid incorrect URL generation
|
86
|
+
Pathname.new(client.base_url).join(ENDPOINT, safe_path).to_s
|
87
|
+
end
|
88
|
+
|
89
|
+
def build_headers(client_correlation_id:, callback_url: nil)
|
90
|
+
value = {
|
91
|
+
"Authorization" => "Bearer #{client.token.access_token}",
|
92
|
+
"Version" => "1.0",
|
93
|
+
"X-CorrelationID" => client_correlation_id,
|
94
|
+
"UserLanguage" => client.user_language,
|
95
|
+
"Cache-Control" => "no-cache",
|
96
|
+
"userAccountIdentifier" => "msisdn;#{client.partner_phone_number}",
|
97
|
+
"partnerName" => client.partner_name
|
98
|
+
}
|
99
|
+
|
100
|
+
value["X-Callback-URL"] = callback_url if callback_url
|
101
|
+
|
102
|
+
value
|
103
|
+
end
|
104
|
+
end
|
105
|
+
end
|
data/lib/mvola.rb
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "logger"
|
4
|
+
require "base64"
|
5
|
+
require "json"
|
6
|
+
require "time"
|
7
|
+
require_relative "mvola/version"
|
8
|
+
require_relative "mvola/errors"
|
9
|
+
require_relative "mvola/client"
|
10
|
+
require_relative "mvola/transaction"
|
11
|
+
|
12
|
+
module MVola
|
13
|
+
class << self
|
14
|
+
attr_accessor :logger
|
15
|
+
end
|
16
|
+
|
17
|
+
# Set up a default logger
|
18
|
+
self.logger = Logger.new($stdout) # Logs to the console
|
19
|
+
logger.level = Logger::INFO # Default log level
|
20
|
+
end
|
@@ -0,0 +1,21 @@
|
|
1
|
+
module MVola
|
2
|
+
class Client
|
3
|
+
class Token
|
4
|
+
attr_reader access_token: String
|
5
|
+
attr_reader scope: String
|
6
|
+
attr_reader token_type: String
|
7
|
+
attr_reader expires_at: Time
|
8
|
+
|
9
|
+
def initialize: (
|
10
|
+
access_token: String,
|
11
|
+
scope: String,
|
12
|
+
token_type: String,
|
13
|
+
expires_at: Time
|
14
|
+
) -> void
|
15
|
+
|
16
|
+
def expired?: () -> bool
|
17
|
+
|
18
|
+
def valid?: () -> bool
|
19
|
+
end
|
20
|
+
end
|
21
|
+
end
|