Class: Mpp::Server::Middleware

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/mpp/server/middleware.rb

Overview

Rack middleware that intercepts requests requiring payment.

The downstream app signals payment is needed by setting env to a hash with at least :amount, and optionally :currency, :recipient, :description, :expires, etc.

Example:

use Mpp::Server::Middleware, handler: my_handler

# In your app:
env["mpp.charge"] = { amount: "1.00" }

Instance Method Summary collapse

Constructor Details

#initialize(app, handler:) ⇒ Middleware

Returns a new instance of Middleware.



21
22
23
24
# File 'lib/mpp/server/middleware.rb', line 21

def initialize(app, handler:)
  @app = T.let(app, T.untyped)
  @handler = T.let(handler, Mpp::Server::MppHandler)
end

Instance Method Details

#call(env) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/mpp/server/middleware.rb', line 27

def call(env)
  authorization = env["HTTP_AUTHORIZATION"]
  status, headers, body = @app.call(env)

  charge_opts = env["mpp.charge"]
  return [status, headers, body] unless charge_opts

  amount = charge_opts[:amount]
  opts = charge_opts.except(:amount)

  result = @handler.charge(authorization, amount, **opts)

  if result.is_a?(Mpp::Challenge)
    resp = Mpp::Server::Decorator.make_challenge_response(result, @handler.realm)
    return [resp["status"], resp["headers"], [resp["body"]]]
  end

  _credential, receipt = result
  headers["Payment-Receipt"] = receipt.to_payment_receipt

  [status, headers, body]
end