Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/ability to apply coupon for price #2

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 57 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ Install the gem and add to the application's Gemfile by executing:
bundle add "monopay-ruby"
```

If bundler is not being used to manage dependencies, install the gem by executing:
If bundler is not being used to manage dependencies, install the gem by executing the:

```ruby
gem install "monopay-ruby"
```

## Usage
## Configuration

Add API token. There are two ways:
First - add to the initializer file:
Expand All @@ -46,10 +46,32 @@ Development: [https://api.monobank.ua/](https://api.monobank.ua/)

Production: [https://fop.monobank.ua/](https://fop.monobank.ua/)

Just get the token and go to earn moneys! 🚀
Just get the token and go to earn money! 🚀


_______________________________________________________________

Optional

You may add a minimum value to your payment:

```ruby
# config/initializers/monopay-ruby.rb
MonopayRuby.configure do |config|
config.min_price = 1
end
```
* 0.01 UAH - it is a minimal valid value for Monobank:
- if you use 1 as an Integer it is equal to 0.01 UAH
- if you use BigDecimal(1) it's equal to 1 UAH

The default value is 1 (0.01 UAH)


### Generate payment request

Simple:

```ruby
# app/controllers/payments_controller.rb
class PaymentsController < ApplicationController
Expand All @@ -59,8 +81,8 @@ class PaymentsController < ApplicationController
"https://example.com/payments/webhook"
)

if payment.create(amount: 100, destination: "Payment description",)
# your success code processing
if payment.create(amount: 100, destination: "Payment description")
# your successful code processing
else
# your error code processing
# flash[:error] = payment.error_messages
Expand All @@ -69,6 +91,35 @@ class PaymentsController < ApplicationController
end
```

With discount:

```ruby
# app/controllers/payments_controller.rb
class PaymentsController < ApplicationController
def create
payment = MonopayRuby::Invoices::SimpleInvoice.new(
"https://example.com",
"https://example.com/payments/webhook"
)

if payment.create(amount: 100, discount: 20, discount_is_fixed: true, destination: "Payment description")
# your successful code processing
else
# your error code processing
# flash[:error] = payment.error_messages
end
end
end
```

Options:
- discount - is an number, which represents a % of discount if discount_is_fixed: false and an amount of discount if discount_is_fixed: true
- discount_is_fixed - a Boolean which sets the type of discount:
- ```true``` fixed amount of discount will be applied, for example a coupon
- ```false``` discount amount will be preceded by %.
* can be Integer, Float or BigDecimal


### Verify transaction

```ruby
Expand All @@ -80,7 +131,7 @@ class PaymentsController < ApplicationController
webhook_validator = MonopayRuby::Webhooks::Validator.new(request)

if webhook_validator.valid?
# your success code processing
# your successful code processing
else
# your error code processing
# flash[:error] = webhook_validator.error_messages
Expand Down
5 changes: 3 additions & 2 deletions lib/monopay-ruby/configuration.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
class MonopayRuby::Configuration
attr_accessor :api_token
attr_accessor :api_token, :min_price

def initialize
@api_token = ENV["MONOBANK_API_TOKEN"] # note ability to use ENV variable in docs
@api_token = ENV["MONOBANK_API_TOKEN"]
@min_price = ENV["MIN_PRICE"] || 1
end
end
21 changes: 11 additions & 10 deletions lib/monopay-ruby/invoices/simple_invoice.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,21 @@ def initialize(redirect_url: nil, webhook_url: nil)
# @param [String] destination - additional info about payment
# @param [String] reference - bill number or other reference
# @return [Boolean] true if invoice was created successfully, false otherwise
def create(amount, destination: nil, reference: nil)
def create(amount, discount: nil, discount_is_fixed: false, destination: nil, reference: nil)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

щось трохи забагато аргументів, по конвеншинам так краще не робити, ну передавати можна, але от явно прописаних вже забагато, макс 3 гуд є, чи близько того


begin
@amount = convert_to_cents(amount)
@min_amount = MonopayRuby::Services::ValidateValue.call(MonopayRuby.configuration.min_price, DEFAULT_CURRENCY, "Minimal amount")
@amount = MonopayRuby::Services::ValidateValue.call(amount, DEFAULT_CURRENCY)

@destination = destination
@reference = reference

if discount.present?
discount = MonopayRuby::Services::ConvertAmount.call(discount, DEFAULT_CURRENCY)

@amount = MonopayRuby::Services::Discount.call(@amount, discount, discount_is_fixed, @min_amount)
end

response = RestClient.post(API_CREATE_INVOICE_URL, request_body, headers)
response_body = JSON.parse(response.body)

Expand Down Expand Up @@ -71,14 +80,6 @@ def request_body
}
}.to_json
end

def convert_to_cents(amount)
if amount.is_a?(BigDecimal)
Money.from_amount(amount, DEFAULT_CURRENCY).cents
else
amount
end
end
end
end
end
9 changes: 9 additions & 0 deletions lib/monopay-ruby/services/base_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module MonopayRuby
module Services
class BaseService
def self.call(*args)
new(*args).call
end
end
end
end
25 changes: 25 additions & 0 deletions lib/monopay-ruby/services/convert_amount.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
require "money"
require "bigdecimal"

module MonopayRuby
module Services
class ConvertAmount < BaseService
attr_reader :amount, :currency

def initialize(amount, currency)
@amount = amount
@currency = currency
end

def call
if amount.is_a?(BigDecimal)
Money.from_amount(amount, currency).cents
elsif amount.is_a?(Integer)
amount
else
raise TypeError, "allowed to use only a BigDecimal or Integer type"
end
end
end
end
end
24 changes: 24 additions & 0 deletions lib/monopay-ruby/services/discount.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module MonopayRuby
module Services
class Discount < BaseService
attr_reader :amount, :discount, :discount_is_fixed, :min_amount

def initialize(amount, discount, discount_is_fixed, min_amount)
@amount = amount
@discount = discount
@discount_is_fixed = discount_is_fixed
@min_amount = min_amount
end

def call
if discount_is_fixed
sum = amount - discount
else
sum = amount * (1 - (discount.to_f / 100))
end

[sum.to_i, min_amount].max
end
end
end
end
37 changes: 37 additions & 0 deletions lib/monopay-ruby/services/validate_value.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
require "bigdecimal"

module MonopayRuby
module Services
class ValidateValue < BaseService
attr_reader :amount, :currency, :type

def initialize(amount, currency, type='Amount')
@amount = amount
@currency = currency
@type = type
end

def call
if amount.is_a?(Integer) || amount.is_a?(BigDecimal)
if amount > 0
MonopayRuby::Services::ConvertAmount.call(amount, currency)
else
raise ValueError, "#{type} must be greater than 0"
end
else
raise TypeError, "#{type} is allowed to be Integer or BigDecimal, got #{amount.class}" unless amount.is_a?(Integer) || amount.is_a?(BigDecimal)
end
end

private

def name(var)
binding.local_variables.each do |name|
value = binding.local_variable_get(name)
return name.to_s if value == var
end
nil
end
end
end
end
1 change: 0 additions & 1 deletion lib/monopay-ruby/webhooks/public_key.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
require "base64"
require "json"

require "pry"
module MonopayRuby
module Webhooks
class PublicKey < MonopayRuby::Base
Expand Down
Loading