Skip to content

Commit

Permalink
Merge pull request #1 from WebGents/rebuild_http
Browse files Browse the repository at this point in the history
Rebuild http
  • Loading branch information
kortirso authored Dec 23, 2017
2 parents 1f086ae + cbf31b2 commit c3cc3f1
Show file tree
Hide file tree
Showing 28 changed files with 190 additions and 371 deletions.
46 changes: 46 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
AllCops:
Exclude:
- bin/*

Metrics/AbcSize:
Enabled: false

Metrics/BlockLength:
Enabled: false

Metrics/ClassLength:
Enabled: false

Metrics/LineLength:
Enabled: false

Metrics/MethodLength:
Enabled: false

Metrics/ModuleLength:
Enabled: false

Metrics/CyclomaticComplexity:
Max: 20

Layout/IndentationWidth:
Width: 4

Layout/CaseIndentation:
EnforcedStyle: case
SupportedStyles:
- case
- end
IndentOneStep: true

Layout/AlignHash:
Enabled: false

Style/GuardClause:
Enabled: false

Style/FileName:
Enabled: false

Style/FormatStringToken:
EnforcedStyle: template
2 changes: 2 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
source 'https://rubygems.org'

git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }

group :test do
gem 'rspec'
gem 'webmock'
Expand Down
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ Actions with payments in MobilePay system.
Add this line to your application's Gemfile:

```ruby
gem 'jose'
gem 'mobilepay'
```

Expand All @@ -25,7 +24,7 @@ Or install it yourself as:

```ruby
require 'mobilepay'
security = Mobilepay::Security.new subscription_key: 'subscription_key'
security = Mobilepay::Security.new subscription_key: 'subscription_key', privatekey: 'key.pvk'
```
merchant_id - Merchant ID, required

Expand Down
2 changes: 1 addition & 1 deletion Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ require 'rspec/core/rake_task'

RSpec::Core::RakeTask.new(:spec)

task :default => :spec
task default: :spec
1 change: 1 addition & 0 deletions lib/mobilepay.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
require_relative 'mobilepay/client'
require_relative 'mobilepay/security'

# Top-level comment
module Mobilepay
class Failure < StandardError; end
end
39 changes: 13 additions & 26 deletions lib/mobilepay/client.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require 'json'
require 'httparty'
require_relative 'client/payment_status'
require_relative 'client/payment_transactions'
require_relative 'client/reservations'
Expand All @@ -9,7 +9,9 @@
require_relative 'requests/generate_signature'

module Mobilepay
# Clients requests
class Client
include HTTParty
include Mobilepay::Client::PaymentStatus
include Mobilepay::Client::PaymentTransactions
include Mobilepay::Client::Reservations
Expand All @@ -19,40 +21,25 @@ class Client
include Mobilepay::Requests
include Mobilepay::Requests::GenerateSignature

attr_reader :merchant_id, :subscription_key, :privatekey, :test_mode, :base_uri
base_uri 'https://api.mobeco.dk/appswitch/api/v1'
format :json

attr_reader :privatekey, :headers, :merchant_id, :body

def initialize(args = {})
@merchant_id = args[:merchant_id] || ''
@subscription_key = args[:subscription_key] || ''
@privatekey = args[:privatekey]
@test_mode = args[:test_mode] || false
@base_uri = 'https://api.mobeco.dk/appswitch/api/v1'
end

private

def call(req, address, args = {})
response = case req
when :get, :put, :delete then http_request(req, address, args)
else raise Failure, 'Undefined type for call'
end
check_response(response)
response
end

def check_response(response)
if response.code != '200'
error_message = response.body.empty? ? response.code : response.body
raise Failure, error_message
end
@headers = { 'Ocp-Apim-Subscription-Key' => args[:subscription_key], 'Content-Type' => 'application/json' }
@merchant_id = args[:merchant_id]
headers['Test-mode'] = 'true' if args[:test_mode] == true
@body = ''
end

def check_args(args)
private def check_args(args)
args.each do |arg_name, value|
if value.nil?
raise Failure, "Invalid argument '#{arg_name}', must be string"
end
end
end
end
end
end
10 changes: 4 additions & 6 deletions lib/mobilepay/client/cancel_reservation.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
module Mobilepay
class Client
# Reservations_CancelReservation
module CancelReservation

# Reservations_CancelReservation
# Cancels a specific reservation
def cancel_reservation(args = {})
check_args(order_id: args[:order_id])
response = call(:delete, "/reservations/merchants/#{merchant_id}/orders/#{args[:order_id]}", { body: '' })
JSON.parse(response.body)
response = request(:delete, "/reservations/merchants/#{merchant_id}/orders/#{args[:order_id]}")
response.parsed_response
rescue Failure => ex
return { error: ex.message }
end

end
end
end
end
11 changes: 5 additions & 6 deletions lib/mobilepay/client/capture_amount.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
module Mobilepay
class Client
# Reservations_CaptureAmount
module CaptureAmount

# Reservations_CaptureAmount
# Captures a previously reserved amount, either in full or partially
def capture_amount(args = {})
check_args(order_id: args[:order_id])
response = call(:put, "/reservations/merchants/#{merchant_id}/orders/#{args[:order_id]}", { body: args[:body] || '' })
JSON.parse(response.body)
@body = args[:body]
response = request(:put, "/reservations/merchants/#{merchant_id}/orders/#{args[:order_id]}")
response.parsed_response
rescue Failure => ex
return { error: ex.message }
end

end
end
end
end
10 changes: 4 additions & 6 deletions lib/mobilepay/client/payment_status.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
module Mobilepay
class Client
# Merchants_GetPaymentStatus
module PaymentStatus

# Merchants_GetPaymentStatus
# Gets the status of a given order
def payment_status(args = {})
check_args(order_id: args[:order_id])
response = call(:get, "/merchants/#{merchant_id}/orders/#{args[:order_id]}", { body: '' })
JSON.parse(response.body)
response = request(:get, "/merchants/#{merchant_id}/orders/#{args[:order_id]}")
response.parsed_response
rescue Failure => ex
return { error: ex.message }
end

end
end
end
end
10 changes: 4 additions & 6 deletions lib/mobilepay/client/payment_transactions.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
module Mobilepay
class Client
# Merchants_GetPaymentTransactions
module PaymentTransactions

# Merchants_GetPaymentTransactions
# Gets the transactions for a given order
def payment_transactions(args = {})
check_args(order_id: args[:order_id])
response = call(:get, "/merchants/#{merchant_id}/orders/#{args[:order_id]}/transactions", { body: '' })
JSON.parse(response.body)
response = request(:get, "/merchants/#{merchant_id}/orders/#{args[:order_id]}/transactions")
response.parsed_response
rescue Failure => ex
return { error: ex.message }
end

end
end
end
end
11 changes: 5 additions & 6 deletions lib/mobilepay/client/refund_amount.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
module Mobilepay
class Client
# Merchants_RefundAmount
module RefundAmount

# Merchants_RefundAmount
# Refunds an amount to the customer based on an order id
def refund_amount(args = {})
check_args(order_id: args[:order_id])
response = call(:put, "/merchants/#{merchant_id}/orders/#{args[:order_id]}", { body: args[:body] || '{}' })
JSON.parse(response.body)
@body = args[:body]
response = request(:put, "/merchants/#{merchant_id}/orders/#{args[:order_id]}")
response.parsed_response
rescue Failure => ex
return { error: ex.message }
end

end
end
end
end
14 changes: 6 additions & 8 deletions lib/mobilepay/client/reservations.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
module Mobilepay
class Client
# Reservations_GetReservations
module Reservations

# Reservations_GetReservations
# Get the reservations for a particular date/time interval, and alternatively also for a specific customer
def reservations(args = {})
check_args(datetime_from: args[:datetime_from], datetime_to: args[:datetime_to])
address = "/reservations/merchants/#{merchant_id}/#{args[:datetime_from]}/#{args[:datetime_to]}"
address += "?customerId=#{args[:customer_id]}" if args[:customer_id]
response = call(:get, address, { body: '{}' })
JSON.parse(response.body)
uri = "/reservations/merchants/#{merchant_id}/#{args[:datetime_from]}/#{args[:datetime_to]}"
uri += "?customerId=#{args[:customer_id]}" if args[:customer_id]
response = request(:get, uri)
response.parsed_response
rescue Failure => ex
return { error: ex.message }
end

end
end
end
end
45 changes: 19 additions & 26 deletions lib/mobilepay/requests.rb
Original file line number Diff line number Diff line change
@@ -1,37 +1,30 @@
require 'net/http'

module Mobilepay
# Common requests for classes
module Requests

private

def http_request(req, address, args = {})
uri = generate_uri(address)
req = generate_request(req, uri)
req = generate_headers(req, args[:body])
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
private def request(type, uri)
add_signature(uri)
response = send_request(type, uri)
check_response(response)
response
end

def generate_uri(address = '')
URI("#{base_uri}#{address}")
private def add_signature(uri)
headers['AuthenticationSignature'] = generate_signature(uri)
end

def generate_request(req, uri)
case req
when :get then Net::HTTP::Get.new(uri)
when :put then Net::HTTP::Put.new(uri)
when :delete then Net::HTTP::Delete.new(uri)
private def send_request(type, uri)
case type
when :get then self.class.get(uri, query: {}, headers: headers)
when :put then self.class.put(uri, query: {}, headers: headers)
when :delete then self.class.delete(uri, query: {}, headers: headers)
end
end

def generate_headers(req, body)
req['Content-Type'] = 'application/json'
req['Ocp-Apim-Subscription-Key'] = subscription_key
req['AuthenticationSignature'] = generate_signature(req) unless privatekey.nil?
req['Test-mode'] = test_mode if test_mode == true
req.body = body
req
private def check_response(response)
if response.code != 200
error_message = response.message.empty? ? response.code : response.message
raise Failure, error_message
end
end

end
end
end
12 changes: 5 additions & 7 deletions lib/mobilepay/requests/generate_signature.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,16 @@

module Mobilepay
module Requests
# Generate signature module
module GenerateSignature

# Generate Authentication Signature
def generate_signature(request)
payload = (request.uri.to_s + request.body.to_s).encode('UTF-8')
def generate_signature(uri)
payload = (Mobilepay::Client.base_uri + uri + body.to_s).encode('UTF-8')
payload_sha1 = Digest::SHA1.digest(payload)
payload_base64 = Base64.strict_encode64(payload_sha1)

jwk = JOSE::JWK.from_pem_file(privatekey)
JOSE::JWS.sign(jwk, payload_base64, { 'alg' => 'RS256', 'typ' => 'JWT' }).compact
JOSE::JWS.sign(jwk, payload_base64, 'alg' => 'RS256', 'typ' => 'JWT').compact
end

end
end
end
end
Loading

0 comments on commit c3cc3f1

Please sign in to comment.