Class: Mobile::Pesa::StkPushStatus

Inherits:
Object
  • Object
show all
Defined in:
lib/mobile/pesa/stk_push_status.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(checkout_request_id, short_code) ⇒ StkPushStatus



19
20
21
22
# File 'lib/mobile/pesa/stk_push_status.rb', line 19

def initialize(checkout_request_id, short_code)
  @checkout_request_id = checkout_request_id
  @short_code = short_code
end

Instance Attribute Details

#checkout_request_idObject (readonly)

Returns the value of attribute checkout_request_id.



13
14
15
# File 'lib/mobile/pesa/stk_push_status.rb', line 13

def checkout_request_id
  @checkout_request_id
end

#short_codeObject (readonly)

Returns the value of attribute short_code.



13
14
15
# File 'lib/mobile/pesa/stk_push_status.rb', line 13

def short_code
  @short_code
end

Class Method Details

.call(checkout_request_id:, short_code:) ⇒ Object



15
16
17
# File 'lib/mobile/pesa/stk_push_status.rb', line 15

def self.call(checkout_request_id:, short_code:)
  new(checkout_request_id, short_code).call
end

Instance Method Details

#callObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mobile/pesa/stk_push_status.rb', line 24

def call
  url = URI("https://sandbox.safaricom.co.ke/mpesa/stkpushquery/v1/query")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Post.new(url)
  request["Content-Type"] = 'application/json'
  request["Authorization"] = "Bearer #{token}"
  request.body = JSON.dump(body)

  response = http.request(request)
  parsed_body = JSON.parse(response.read_body)

  if parsed_body.key?("errorCode")
    error = OpenStruct.new(
      error_code: parsed_body["errorCode"],
      error_message: parsed_body["errorMessage"],
      request_id: parsed_body["requestId"]
    )
    OpenStruct.new(result: nil, error: error)
  else
    result = OpenStruct.new(
      merchant_request_id: parsed_body["MerchantRequestID"],
      checkout_request_id: parsed_body["CheckoutRequestID"],
      response_code: parsed_body["ResponseCode"],
      response_description: parsed_body["ResponseDescription"],
      result_desc: parsed_body["ResultDesc"],
      result_code: parsed_body["ResultCode"]
    )
    OpenStruct.new(result: result, error: nil)
  end
rescue JSON::ParserError => error
  OpenStruct.new(result: nil, error: error)
end