public
Description: Simple wrapper for the Braintree APIs that uses Camping
Homepage: http://developer.getbraintree.com
Clone URL: git://github.com/braintree/braintree-utili-tool.git
ch0wda (author)
Thu Apr 10 10:30:18 -0700 2008
commit  a75b79794622317b44f66233c9722797e2a87bec
tree    d242c92c5d0f525f35b24fc3f612028276c6ebee
parent  d5195cebef0b250691de2755f806af2def15a4a8
braintree-utili-tool / utili_tool.rb
100755 439 lines (393 sloc) 12.975 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#!/usr/bin/env ruby
 
%w( rubygems mime/types camping xmlsimple
digest/md5 net/https redcloth pp).each { |lib| require lib }
 
Camping.goes :UtiliTool
 
module UtiliTool::Models
 
  class Hasher
    attr_accessor :variables
    def initialize(variables = nil)
      self.variables = variables.nil? ? [] : variables
    end
    
    def string_to_hash; variables.join("|") end
 
    def hash
      self.variables.any? ? Digest::MD5.hexdigest(self.string_to_hash) : ""
    end
 
    def hashed?; self.variables.length > 0 ? true : false end
  end
 
  class Braintree
    attr_accessor :orderid, :amount, :key, :key_id, :time
 
    def initialize(attributes = nil)
      unless attributes.nil?
        attributes.each { |k,v| self.send("#{k}=", v) } unless attributes.nil?
        self.time = self.class.current_time unless attributes.include?(:time)
      else
        self.time = self.class.current_time
      end
    end
    
    def self.current_time
      Time.now.getutc.strftime("%Y%m%d%H%m%S")
    end
  end
 
  class GatewayRequest < Braintree
    attr_accessor :api, :url_base, :uri_string
    attr_reader :url
 
    def initialize(attributes = nil, form_inputs = nil)
      attributes.each { |k,v| self.send("#{k}=", v)} unless attributes.nil?
      determine_api_url_base
      self.uri_string = create_uri_string_from_form_inputs(form_inputs) unless form_inputs.nil?
    end
 
    def url
      [self.url_base, self.uri_string].join("?")
    end
 
    # Sending a request relies on net/https instead of open-uri because
    # it's easier to skip the SSL validity checks. In Ruby 1.9, this
    # won't be necessary.
    def send_request
      uri = URI.parse self.url
      server = Net::HTTP.new uri.host, uri.port
      server.use_ssl = uri.scheme == 'https'
      server.verify_mode = OpenSSL::SSL::VERIFY_NONE
      # use POST instead of GET
      response = server.post self.url_base, self.uri_string
      return response.body
    end
    alias response send_request
 
    private
    def determine_api_url_base
      if api == "query"
        self.url_base = "https://secure.braintreepaymentgateway.com/api/query.php"
      else
        self.url_base = "https://secure.braintreepaymentgateway.com/api/transact.php"
      end
    end
 
    # Takes a hash and returns a query string. If there is a field called
    # 'quick_query', the key will be dropped, and only the value will be used.
    def create_uri_string_from_form_inputs(form_inputs)
      uri_array = []
      form_inputs.delete_if { |key,value| value.strip == "" }
      form_inputs.each do |key, value|
        key == 'quick_query' ? uri_array << value : uri_array << "#{key}=#{value}"
      end
      uri_array.join("&")
    end
  end
 
  class GatewayResponse < Braintree
    attr_accessor :response_body, :format, :formatted_response_body
    def initialize(response_body, format = nil)
      self.response_body = response_body
      self.format = format
      self.formatted_response_body = format_response_body
    end
 
    def to_hash
      if self.format.nil?
        response_hash = { }
        self.response_body.split("&").each do |pair|
        pair_array = pair.split("=")
          response_hash[pair_array[0]] = pair_array[1]
        end
        response_hash.delete_if { |key, value| value.nil? }
      else
        response_hash = XmlSimple.xml_in(self.response_body, { 'SupressEmpty' => true, 'NormaliseSpace' => 2 })
      end
      return response_hash
    end
  
    private
    def format_response_body
      unless self.format.nil?
        xml_oo = XmlSimple.xml_in(self.response_body, { 'SuppressEmpty' => true })
        xml_oo_out = XmlSimple.xml_out(xml_oo, { 'NoEscape' => true })
        formatted = xml_oo_out.gsub("<", "&lt;").gsub(">", "&gt;")
        return formatted
      end
    end
  end
end
 
module UtiliTool::Controllers
  # class Something < R 'route'
  # include Responder
  #
  # def get
  # ... important code ...
  #
  # respond_to do |format|
  # format.html { render :something }
  # format.text { "Just some text." }
  # format.yaml { "Something neat!".to_yaml }
  # format.xml { "Also, XML.".to_xml }
  # end
  # end
  # end
  module Responder
    def respond_to
      yield response = Response.new(env.HTTP_ACCEPT)
      @headers['Content-Type'] = response.content_type
      response.body
    end
    
    class Response
      attr_reader :body, :content_type
      def initialize(accept) @accept = accept end
      
      TYPES = {
        :yaml => %w[application/yaml text/yaml],
        :text => %w[text/plain],
        :html => %w[text/html */* application/html],
        :xml => %w[application/xml]
      }
      
      def method_missing(method, *args)
        if TYPES[method] && @accept =~ Regexp.union(*TYPES[method])
          @content_type = TYPES[method].first
          @body = yield if block_given?
        end
      end
    end
  end
  
  class Index < R '/'
    include Responder
    def get
      respond_to do |format|
        format.html { render :index }
      end
    end
  end
 
  class Hasher < R '/hasher'
    include Responder
    def get
      @gateway = Braintree.new
      respond_to do |format|
        format.html { render :hasher }
      end
    end
 
    def post
      @gateway = Braintree.new
      @hasher = UtiliTool::Models::Hasher.new([input.orderid, input.key,
                                             input.time, input.amount])
      respond_to do |format|
        format.html { render :hasher }
      end
    end
  end
  
  # This action gives you a text area to input values to. You
  # can then post this directly to the gateway.
  class QuickGet < R '/quick_get'
    include Responder
    def get
      @gateway_request = GatewayRequest.new({ :api => "payment" })
      respond_to do |format|
        format.html { render :quick_get }
      end
    end
 
    def post
      @gateway_request = GatewayRequest.new({ :api => "payment" }, input)
      @gateway_response = GatewayResponse.new(@gateway_request.response)
      respond_to do |format|
        format.html { render :quick_get }
      end
    end
  end
 
  class QuickQuery < R '/quick_query'
    include Responder
    def get
      @gateway_request = GatewayRequest.new({ :api => "query" })
      respond_to do |format|
        format.html { render :quick_query }
      end
    end
 
    def post
      @gateway_request = GatewayRequest.new( { :api, "query"}, input )
      @gateway_response = GatewayResponse.new(@gateway_request.response, "xml")
      respond_to do |format|
        format.html { render :quick_query }
      end
    end
  end
  
  class Assets < R('/static/(.+)')
    PATH = File.expand_path("#{File.dirname(__FILE__)}")
    def get file
      if file.include? '..'
        @status = '403'; return '403 - Invalid path'
      else
        type = (MIME::Types.type_for(file)[0] || '/text/plain').to_s
        @headers['Content-Type'] = type
        @headers['X-Sendfile'] = File.join PATH, 'static', file
      end
    end
  end
end
 
module UtiliTool::Helpers
  def site_title; "Braintree Util-i-Tool" end
  def split_string(string); string.split("&").join("&\n"); end
 
  def static_content(file)
    path = File.expand_path("#{File.dirname(__FILE__)}")
    file_path = File.join path, 'contents', "#{file}.textile"
    RedCloth.new(File.read(file_path)).to_html
  end
 
  def word_wrap(text, line_width = 80)
    text.split("&").collect do |line|
      line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip : line
    end * "\n"
  end
end
 
module UtiliTool::Views
 
  Camping::Mab.set(:indent, 2)
  
  # Layout
  def layout
    xhtml_transitional do
      head do
        title site_title
        link(:rel => 'stylesheet', :type => 'text/css',
             :href => R(Assets, 'utili_tool.css'), :media => 'screen')
# script(:src => R(Assets, 'jquery-1.2.3.js'), :type => 'text/javascript')
# script(:src => R(Assets, 'utili-tool.js', :type => 'text/javascript'))
      end
      body do
        div.wrapper! do
          div.masthead! do
            h1 site_title
          end
          div.container! do
            div.sidebar! do
              _sidebar
            end
            div.content! do
              self << yield
            end
          end
          div.footer! do
            [["Braintree Payment Solutions", "http://www.getbraintree.com"],
             ["Braintree Developer Community", "http://developer.getbraintree.com"],
             ["Braintree Merchant Login", "https://secure.braintreepaymentgateway.com/merchants/login.php"],
            ].map do |txt, link, title|
              a txt, :href => link, :title => txt
            end.join(" | ")
          end
        end
        _google_analytics
      end
    end
  end
 
  # Partials
  def _sidebar
    h3 "Tools"
    _navigation
  end
 
  def _navigation
    ul.navigation do
      li { a "Home", :href => R(Index), :title => "Home",
        :accesskey => "H" }
      li { a "Hasher", :href => R(Hasher), :title => "Hasher",
        :accesskey => "M" }
      li { a "QuickGet", :href => R(QuickGet), :title => "QuickGet",
        :accesskey => "G"}
      li { a "QuickQuery", :href => R(QuickQuery), :title => "QuickQuery",
        :accesskey => "Q"}
    end
  end
 
  def _google_analytics
    script(:type => "text/javascript") do
      %[var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));]
    end
    script(:type => "text/javascript") do
      %[var pageTracker = _gat._getTracker("UA-1885256-7");
pageTracker._initData();
pageTracker._trackPageview();]
    end
  end
  
  # Actions
  def index
    div.static do; static_content("index"); end
  end
 
  def hasher
    h2 "Braintree MD5 Hash Generator"
    div.static do; static_content("hasher"); end
    if @hasher
      div.response do
        table.response do
          tr do
            td "The string to hash was:"
            td { code @hasher.string_to_hash}
          end
          tr do
            td "The MD5 hash generated was:"
            td { code @hasher.hash }
          end
        end
      end
    end
    form({ :method => 'post', :action => R(Hasher)}) do
      fieldset do
        legend "Input Values to Hash"
        p { label 'Order Id', :for => 'orderid'; br;
            input :type => 'text', :name => "orderid" }
        p { label 'Amount', :for => 'amount'; br;
            input :type => 'text', :name => "amount" }
        p { label 'Time', :for => 'time'; br;
            input :type => 'text', :name => "time",
                  :value => @gateway.time }
        p { label 'Key', :for => 'key'; br;
            input :type => 'text', :name => "key" }
        input :type => 'submit', :value => 'Submit'
      end
    end
  end
 
  def quick_get
    h2 "QuickGet"
    div.static do; static_content("quick_get"); end
    unless @gateway_response.nil?
      div.response do
        h3 "Gateway Response"
        p { code { word_wrap(@gateway_request.uri_string) }}
        table.response(:cellspacing => "0") do
          tr.header do
            th "Param"
            th "Value"
          end
          @gateway_response.to_hash.each do |key, value|
            tr do
              td key
              td { code value }
            end
          end
        end
      end
    end
    form({ :method => 'post', :action => R(QuickGet)}) do
      fieldset do
        legend "Input a query string"
        p { label 'Username', :for => 'username'; br;
            input :type => 'text', :name => "username" }
        p { label 'Password', :for => 'password'; br;
          input :type => 'text', :name => "password" }
        p { label 'Query', :for => 'quick_query'; br;
            textarea :name => "quick_query", :rows => 5, :cols => 55 }
        input :type => 'submit', :value => 'Submit'
      end
    end
  end
 
  def quick_query
    h2 "QuickQuery"
    div.static do; static_content("quick_query"); end
    unless @gateway_response.nil?
      div.response do
        h3 "Raw Gateway Response"
        p "Better formatting is on it's way."
        p { code { word_wrap(@gateway_request.uri_string) }}
        code do
          @gateway_response.formatted_response_body
        end
      end
    end
    form({ :method => 'post', :action => R(QuickQuery)}) do
      fieldset do
        legend "Input a query string"
        p { label 'Username', :for => 'username'; br;
            input :type => 'text', :name => "username" }
        p { label 'Password', :for => 'password'; br;
          input :type => 'text', :name => "password" }
        p { label 'Query', :for => 'quick_query'; br;
            textarea :name => "quick_query", :rows => 5, :cols => 55 }
        input :type => 'submit', :value => 'Submit'
      end
    end
  end
end
 
def UtiliTool.create; end