kco_ruby 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 0eeef43a4c70e3518d9e88ff0ebebd007f9e2c9f
4
+ data.tar.gz: 717eb5774688218a4e04e20bc0238e09c558b431
5
+ SHA512:
6
+ metadata.gz: 27dc8c2587d037ad30dd63521a9f26497ec2604fdd94f1cd71e3ce68610e7905c59b81086781c48a47c60f631197dabc7b73ba9a4373f18f4d1eadc0364b869d
7
+ data.tar.gz: 0abd853cf9d3c0ee02bce0c93363c868cc89b9be118b4a24c37d066819ea8d77a6c3a6b5b893cb842d65fb7ebb60a8ca82517ad2790bfcd4e97356e2c02c681d
data/.gitignore ADDED
@@ -0,0 +1,22 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
18
+ *.bundle
19
+ *.so
20
+ *.o
21
+ *.a
22
+ mkmf.log
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in kco_ruby.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
data/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # KcoRuby
2
+
3
+ This gem is a port from Klarnas python API for Klarna Checkout
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'kco_ruby'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install kco_ruby
18
+
19
+ ## Usage
20
+
21
+ ```
22
+ cart = [
23
+ {
24
+ 'quantity' => 1,
25
+ 'reference' => '123456789',
26
+ 'name' => 'Klarna t-shirt',
27
+ 'unit_price' => 12300,
28
+ 'discount_rate' => 1000,
29
+ 'tax_rate' => 2500
30
+ }, {
31
+ 'quantity' => 1,
32
+ 'type' => 'shipping_fee',
33
+ 'reference' => 'SHIPPING',
34
+ 'name' => 'Shipping Fee',
35
+ 'unit_price' => 4900,
36
+ 'tax_rate' => 2500
37
+ }
38
+ ]
39
+
40
+ create_data = {}
41
+ create_data["cart"] = {"items" => []}
42
+
43
+ cart.each do |item|
44
+ create_data["cart"]["items"] << item
45
+ end
46
+
47
+
48
+ create_data['purchase_country'] = 'SE'
49
+ create_data['purchase_currency'] = 'SEK'
50
+ create_data['locale'] = 'sv-se'
51
+ create_data['merchant'] = {
52
+ 'id' => '12345',
53
+ 'terms_uri' => 'http://example.com/terms.html',
54
+ 'checkout_uri' => 'http://example.com/checkout',
55
+ 'confirmation_uri' => ('http://example.com/thank-you' +
56
+ '?sid=123&klarna_order={checkout.order.uri}'),
57
+ 'push_uri' => ('http://example.com/push' +
58
+ '?sid=123&klarna_order={checkout.order.uri}')
59
+ }
60
+
61
+ KcoRuby::Order.base_uri = 'https://checkout.testdrive.klarna.com/checkout/orders'
62
+ KcoRuby::Order.content_type = 'application/vnd.klarna.checkout.aggregated-order-v2+json'
63
+
64
+ connector = KcoRuby.create_connector('secret')
65
+
66
+ order = KcoRuby::Order.new(connector)
67
+ order.create(create_data)
68
+ order.fetch
69
+ ```
70
+
71
+ ## Documentation
72
+ You can use the official documentation from http://developers.klarna.com for Python with one exception,
73
+ all classes are found in KcoRuby module
74
+
75
+ ## Todo
76
+ Add more tests for not so happy paths
77
+ Add more examples
78
+ Add Exception classes
79
+
80
+ ## Contributing
81
+
82
+ 1. Fork it ( https://github.com/[my-github-username]/kco_ruby/fork )
83
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
84
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
85
+ 4. Push to the branch (`git push origin my-new-feature`)
86
+ 5. Create a new Pull Request
87
+
88
+ ## License
89
+ The library is released under Apache License, Version 2.0
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+
3
+
4
+ task :console do
5
+ exec "irb -r kco_ruby -I ./lib"
6
+ end
data/example.rb ADDED
@@ -0,0 +1,56 @@
1
+ require 'kco_ruby'
2
+ require 'sinatra'
3
+ require 'pp'
4
+
5
+ get '/checkout' do
6
+ cart = [
7
+ {
8
+ 'quantity' => 1,
9
+ 'reference' => '123456789',
10
+ 'name' => 'Klarna t-shirt',
11
+ 'unit_price' => 12300,
12
+ 'discount_rate' => 1000,
13
+ 'tax_rate' => 2500
14
+ }, {
15
+ 'quantity' => 1,
16
+ 'type' => 'shipping_fee',
17
+ 'reference' => 'SHIPPING',
18
+ 'name' => 'Shipping Fee',
19
+ 'unit_price' => 4900,
20
+ 'tax_rate' => 2500
21
+ }
22
+ ]
23
+
24
+ create_data = {}
25
+ create_data["cart"] = {"items" => []}
26
+
27
+ cart.each do |item|
28
+ create_data["cart"]["items"] << item
29
+ end
30
+
31
+
32
+ create_data['purchase_country'] = 'SE'
33
+ create_data['purchase_currency'] = 'SEK'
34
+ create_data['locale'] = 'sv-se'
35
+ create_data['merchant'] = {
36
+ 'id' => 'eid',
37
+ 'terms_uri' => 'http://example.com/terms.html',
38
+ 'checkout_uri' => 'http://example.com/checkout',
39
+ 'confirmation_uri' => ('http://example.com/thank-you' +
40
+ '?sid=123&klarna_order={checkout.order.uri}'),
41
+ 'push_uri' => ('http://example.com/push' +
42
+ '?sid=123&klarna_order={checkout.order.uri}')
43
+ }
44
+
45
+ KcoRuby::Order.base_uri = 'https://checkout.testdrive.klarna.com/checkout/orders'
46
+ KcoRuby::Order.content_type = 'application/vnd.klarna.checkout.aggregated-order-v2+json'
47
+
48
+ connector = KcoRuby.create_connector('secret')
49
+
50
+ order = KcoRuby::Order.new(connector)
51
+ order.create(create_data)
52
+ order.fetch
53
+
54
+ puts order.location
55
+ order["gui"]["snippet"]
56
+ end
data/kco_ruby.gemspec ADDED
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'kco_ruby/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "kco_ruby"
8
+ spec.version = KcoRuby::VERSION
9
+ spec.authors = ["Peter Hagström"]
10
+ spec.email = ["peter@significantbit.se"]
11
+ spec.summary = "A port of Klarna Checkout API to Ruby"
12
+ spec.description = "Klarna Checkout library"
13
+ spec.homepage = "https://github.com/significantbit/kco_ruby"
14
+ spec.license = "Apache 2"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0")
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_dependency "sys-uname", "~> 0.9", '> 0.9.1'
22
+ spec.add_development_dependency "bundler", "~> 1.6"
23
+ spec.add_development_dependency "rake", "~> 10.3"
24
+ spec.add_development_dependency "rspec", "~> 3.1"
25
+ spec.add_development_dependency "webmock", "~> 1.8"
26
+ spec.add_development_dependency "simplecov", "~> 0.9"
27
+ end
@@ -0,0 +1,23 @@
1
+ require 'json/ext'
2
+ require 'net/http'
3
+
4
+ module KcoRuby
5
+
6
+ #Responsible for connections against API
7
+ class Connector
8
+ attr_reader :user_agent, :digester
9
+
10
+ def initialize(user_agent, digester)
11
+ @user_agent = user_agent
12
+ @digester =digester
13
+ end
14
+
15
+ #Apply will carryout the order with the collaborators
16
+ def apply(method, resource, options={})
17
+ uri = URI(options['url'] || resource.location)
18
+ request_context = RequestContext.new(uri, resource, self)
19
+ request_context.parse(method, options)
20
+ ResponseHandler.new(request_context.perform_request, resource).handle_response
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,15 @@
1
+ require 'Digest'
2
+ module KcoRuby
3
+ #Creates a digester proc
4
+ def self.create_digester(secret)
5
+ lambda { |string|
6
+ digest = Digest::SHA2.new
7
+ if string
8
+ digest.update(string)
9
+ end
10
+ digest.update(secret)
11
+ digest.base64digest
12
+ }
13
+ end
14
+ end
15
+
@@ -0,0 +1,91 @@
1
+ module KcoRuby
2
+ #This class represent an Order
3
+ class Order
4
+ include Enumerable
5
+
6
+ class << self
7
+ attr_accessor :content_type, :base_uri
8
+ end
9
+
10
+ def initialize(connector, uri=nil)
11
+ @connector =connector
12
+ self.location = uri
13
+ @data = {}
14
+ end
15
+
16
+ #Set location
17
+ def location=(value)
18
+ @location = value.to_s if value
19
+ end
20
+
21
+ #Get location
22
+ def location
23
+ @location
24
+ end
25
+
26
+ #Get value for key
27
+ def [](key)
28
+ @data[key.to_s]
29
+ end
30
+
31
+ #Set a specific key to value
32
+ def []=(key, value)
33
+ @data[key.to_s]=value
34
+ end
35
+
36
+ #Keys returns all keys for order data
37
+ def keys
38
+ @data.keys
39
+ end
40
+
41
+ #Implementation of Enumerable, good for iteration over data
42
+ def each
43
+ @data.each {|key, value| yield key, value}
44
+ end
45
+
46
+ #Returns order content type
47
+ def content_type
48
+ Order.content_type
49
+ end
50
+
51
+ #Sets the order data
52
+ def parse(data)
53
+ @data = data
54
+ end
55
+
56
+ #Returns the order data
57
+ def marshal
58
+ @data
59
+ end
60
+
61
+ #Used when creating a new order
62
+ def create(data)
63
+ options = {
64
+ "url" => Order.base_uri,
65
+ "data" => data
66
+ }
67
+
68
+ @connector.apply(:post, self, options)
69
+ end
70
+
71
+ #When fetching a order that already exists
72
+ def fetch
73
+ options = {
74
+ "url" => @location
75
+ }
76
+
77
+ @connector.apply(:get, self, options)
78
+ end
79
+
80
+ #Used when updating order information, ie. order status completed
81
+ def update(data)
82
+ options = {
83
+ "url" => @location,
84
+ "data" => data
85
+ }
86
+
87
+ @connector.apply(:post, self, options)
88
+ end
89
+
90
+ end
91
+ end
@@ -0,0 +1,65 @@
1
+ module KcoRuby
2
+ #RequestContext is responsible for building the correct request
3
+ class RequestContext
4
+
5
+ def initialize(uri, resource, connector)
6
+ @uri = uri
7
+ @resource = resource
8
+ @connector = connector
9
+ end
10
+
11
+ def parse(method, options)
12
+ case method
13
+ when :get
14
+ create_get_request
15
+ when :post
16
+ create_post_request(options['data'] || @resource.marshal)
17
+ else
18
+ raise Exception.new("#{method} is not a valid HTTP method")
19
+ end
20
+ end
21
+
22
+
23
+ def perform_request
24
+ Net::HTTP.start(@uri.hostname,
25
+ @uri.port,
26
+ :use_ssl => @uri.scheme == 'https') do |http|
27
+ http.request(@request)
28
+ end
29
+ end
30
+
31
+ private
32
+ def create_get_request
33
+ @request = Net::HTTP::Get.new(@uri)
34
+ add_headers
35
+ end
36
+
37
+ def create_post_request(data)
38
+ @request = Net::HTTP::Post.new(@uri)
39
+ add_payload(data)
40
+ add_payload_headers
41
+ end
42
+
43
+
44
+ def add_payload(data)
45
+ @request.body = data.to_json
46
+ end
47
+
48
+ def add_payload_headers
49
+ @request['User-agent'] = @connector.user_agent.to_s
50
+ @request['Content-Type'] = @resource.content_type.to_s
51
+ set_authorization(@request.body)
52
+ @request['Accept'] = @request['Content-Type']
53
+ end
54
+
55
+ def add_headers
56
+ @request['User-agent'] = @connector.user_agent.to_s
57
+ set_authorization()
58
+ @request['Accept'] = @resource.content_type
59
+ end
60
+
61
+ def set_authorization(data='')
62
+ @request['Authorization'] = "Klarna #{@connector.digester.call(data)}"
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,40 @@
1
+ module KcoRuby
2
+
3
+ #When a Response is created this class describe all actions that needs to happen with that response
4
+ class ResponseHandler
5
+ def initialize(response, resource)
6
+ @resource = resource
7
+ @response = response
8
+ end
9
+
10
+ def handle_response
11
+ case @response
12
+ when Net::HTTPOK
13
+ update_resource_data
14
+ when Net::HTTPCreated
15
+ update_resource_location
16
+ else
17
+ raise Exception.new("Invalid response #{@response.inspect}")
18
+ end
19
+ end
20
+
21
+ def location
22
+ @response['location']
23
+ end
24
+
25
+ def data
26
+ @response.body.strip
27
+ end
28
+
29
+ private
30
+
31
+ def update_resource_location
32
+ @resource.location = location if location
33
+ end
34
+
35
+ def update_resource_data
36
+ @resource.parse JSON.parse(data) if data != ""
37
+ end
38
+
39
+ end
40
+ end
@@ -0,0 +1,48 @@
1
+ require "kco_ruby/version"
2
+ require 'sys/uname'
3
+
4
+ module KcoRuby
5
+
6
+ #Responsible for creating User agent strings
7
+ class UserAgent
8
+ include Sys
9
+
10
+ def initialize
11
+ # Components of the user-agent
12
+ @fields = []
13
+ add_field(UserAgentField.new('Library', "Significantbit.KCO.ApiWrapper", KcoRuby::VERSION))
14
+ add_field(UserAgentField.new('OS', Uname.sysname, RUBY_PLATFORM))
15
+ add_field(UserAgentField.new('Language', "Ruby", RUBY_VERSION))
16
+ end
17
+
18
+ def add_field(field)
19
+ @fields << field
20
+ end
21
+
22
+ def to_s
23
+ @fields.map { |field| field.to_s }.join(" ")
24
+ end
25
+ end
26
+
27
+ #The field class is used to describe a UserAgent field
28
+ class UserAgentField
29
+ attr_accessor :identifier, :name, :version
30
+ attr_writer :options
31
+
32
+ def initialize(identifier, name, version, options = nil)
33
+ @identifier = identifier
34
+ @name = name
35
+ @version = version
36
+ @options = options
37
+ end
38
+
39
+ def to_s
40
+ ["#{@identifier}/#{@name}_#{@version}", options_as_string].join(" ").strip
41
+ end
42
+
43
+ def options_as_string
44
+ "(#{@options.join(" ; ")})" if @options
45
+ end
46
+ end
47
+
48
+ end
@@ -0,0 +1,3 @@
1
+ module KcoRuby
2
+ VERSION = "0.0.1"
3
+ end
data/lib/kco_ruby.rb ADDED
@@ -0,0 +1,14 @@
1
+ require "kco_ruby/user_agent"
2
+ require "kco_ruby/digester"
3
+ require "kco_ruby/order"
4
+ require "kco_ruby/request_context"
5
+ require "kco_ruby/response_handler"
6
+
7
+ require "kco_ruby/connector"
8
+
9
+ module KcoRuby
10
+ def self.create_connector(secret)
11
+ KcoRuby::Connector.new(UserAgent.new, KcoRuby.create_digester(secret))
12
+ end
13
+ end
14
+
@@ -0,0 +1,96 @@
1
+ require 'spec_helper'
2
+
3
+ describe KcoRuby::Connector do
4
+ let(:user_agent) { instance_double KcoRuby::UserAgent }
5
+ let(:digester) { double KcoRuby.create_digester('secret') }
6
+ let(:resource) { double KcoRuby::Order }
7
+ subject { KcoRuby::Connector.new(user_agent, digester) }
8
+
9
+ describe "#apply" do
10
+ it "should set correct headers on GET" do
11
+ expect(digester).to receive(:call).with('').and_return('digest')
12
+ expect(resource).to receive(:content_type).and_return("application/json")
13
+ expect(user_agent).to receive(:to_s).and_return("user-agent")
14
+ expect(resource).to receive(:parse).with({"item" => "foo"})
15
+
16
+ stub_request(:get, "http://test/").
17
+ with(:headers => {'User-Agent' => 'user-agent',
18
+ 'Authorization' => 'Klarna digest'}).
19
+ to_return(:status => 200, :body => '{"item": "foo"}', :headers => {})
20
+
21
+ subject.apply(:get, resource, {'url' => 'http://test'})
22
+ end
23
+
24
+ it "should send data instead of marshal of order when data option is set" do
25
+ expect(resource).to receive(:content_type).and_return("application/json")
26
+ expect(user_agent).to receive(:to_s).and_return("user-agent")
27
+ expect(digester).to receive(:call).with('{"foo":"bar"}').and_return('digest')
28
+ expect(resource).to receive(:location=).with("http://test/")
29
+
30
+ stub_request(:post, "http://test/").
31
+ with(:body => "{\"foo\":\"bar\"}",
32
+ :headers => {'User-Agent' => 'user-agent',
33
+ 'Authorization' => 'Klarna digest'}).
34
+ to_return(:status => 201, :headers => {location:'http://test/'})
35
+
36
+ subject.apply(:post, resource, {'url' => 'http://test', 'data' => {foo: 'bar'}})
37
+ end
38
+
39
+ it "should use digester for POST request" do
40
+ expect(resource).to receive(:marshal).and_return({"foo" => 'bar'})
41
+ expect(resource).to receive(:location).and_return("http://test")
42
+ expect(resource).to receive(:content_type).and_return("application/json")
43
+
44
+ expect(digester).to receive(:call).with('{"foo":"bar"}').and_return('test-digest')
45
+ expect(user_agent).to receive(:to_s).and_return("user-agent")
46
+ expect(resource).to receive(:parse).with({"foo" => "bar"})
47
+
48
+ stub_request(:post, "http://test/").
49
+ with(:headers => {
50
+ 'User-Agent' => 'user-agent',
51
+ 'Authorization' => 'Klarna test-digest'}).
52
+ to_return(:status => 200, :body => '{"foo": "bar"}', :headers => {})
53
+
54
+ subject.apply(:post, resource)
55
+ end
56
+
57
+ it "should update location on 201 " do
58
+ expect(resource).to receive(:marshal).and_return({"foo" => 'bar'})
59
+ expect(resource).to receive(:location).and_return("http://test")
60
+ expect(resource).to receive('location=').with('http://updated')
61
+ expect(resource).to receive(:content_type).and_return("application/json")
62
+
63
+ expect(digester).to receive(:call).with('{"foo":"bar"}').and_return('test-digest')
64
+ expect(user_agent).to receive(:to_s).and_return("user-agent")
65
+ stub_request(:post, "http://test/").
66
+ with(:headers => {
67
+ 'User-Agent' => 'user-agent',
68
+ 'Authorization' => 'Klarna test-digest'}).
69
+ to_return(:status => 201, :body => '{"foo": "bar"}', :headers => {location: 'http://updated'})
70
+
71
+ subject.apply(:post, resource)
72
+ end
73
+
74
+ it "should raise exception on wrong status code " do
75
+ expect(resource).to receive(:location).and_return("http://test")
76
+ expect(resource).to receive(:content_type).and_return("application/json")
77
+
78
+ expect(digester).to receive(:call).with('').and_return('test-digest')
79
+ expect(user_agent).to receive(:to_s).and_return("user-agent")
80
+ stub_request(:get, "http://test/").
81
+ with(:headers => {
82
+ 'User-Agent' => 'user-agent',
83
+ 'Authorization' => 'Klarna test-digest'}).
84
+ to_return(:status => 404, :body => 'not found', :headers => {})
85
+
86
+ expect { subject.apply(:get, resource) }.to raise_error
87
+ end
88
+
89
+ it "should raise exception on wrong method type" do
90
+ expect(resource).to receive(:location).and_return("http://test")
91
+ expect { subject.apply(:patch, resource) }.to raise_error
92
+ end
93
+
94
+ end
95
+
96
+ end
@@ -0,0 +1,14 @@
1
+ require 'spec_helper'
2
+
3
+ describe KcoRuby do
4
+ describe "#call" do
5
+ it "returns valid digest" do
6
+ expected = "MO/6KvzsY2y+F+/SexH7Hyg16gFpsPDx5A2PtLZd0Zs="
7
+ data = '{"eid":1245,"goods_list":[{"artno":"id_1","name":'\
8
+ '"product","price":12345,"vat":25,"qty":1}],"currency":"SEK"'\
9
+ ',"country":"SWE","language":"SV"}'
10
+ digester = KcoRuby.create_digester("mySecret")
11
+ expect(digester.call(data)).to eq(expected)
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,68 @@
1
+ require 'spec_helper'
2
+
3
+ describe "Render checkout" do
4
+ let(:connector){ KcoRuby.create_connector('secret') }
5
+
6
+ describe "#create" do
7
+ it "should get gui snippet" do
8
+
9
+ cart = [
10
+ {
11
+ 'quantity' => 1,
12
+ 'reference' => '123456789',
13
+ 'name' => 'Klarna t-shirt',
14
+ 'unit_price' => 12300,
15
+ 'discount_rate' => 1000,
16
+ 'tax_rate' => 2500
17
+ }, {
18
+ 'quantity' => 1,
19
+ 'type' => 'shipping_fee',
20
+ 'reference' => 'SHIPPING',
21
+ 'name' => 'Shipping Fee',
22
+ 'unit_price' => 4900,
23
+ 'tax_rate' => 2500
24
+ }
25
+ ]
26
+
27
+ create_data = {}
28
+ create_data["cart"] = {"items" => []}
29
+
30
+ cart.each do |item|
31
+ create_data["cart"]["items"] << item
32
+ end
33
+
34
+ create_data['purchase_country'] = 'SE'
35
+ create_data['purchase_currency'] = 'SEK'
36
+ create_data['locale'] = 'sv-se'
37
+ create_data['merchant'] = {
38
+ 'id' => '12345',
39
+ 'terms_uri' => 'http://example.com/terms.html',
40
+ 'checkout_uri' => 'http://example.com/checkout',
41
+ 'confirmation_uri' => ('http://example.com/thank-you' +
42
+ '?sid=123&klarna_order={checkout.order.uri}'),
43
+ 'push_uri' => ('http://example.com/push' +
44
+ '?sid=123&klarna_order={checkout.order.uri}')
45
+ }
46
+
47
+ KcoRuby::Order.base_uri = 'https://checkout.testdrive.klarna.com/checkout/orders'
48
+ KcoRuby::Order.content_type = 'application/vnd.klarna.checkout.aggregated-order-v2+json'
49
+
50
+ order = KcoRuby::Order.new(connector)
51
+
52
+ stub_request(:post, "https://checkout.testdrive.klarna.com/checkout/orders").
53
+ to_return(:status => 201, :body => "", :headers => {location: 'https://order-url/item'})
54
+
55
+ order.create(create_data)
56
+
57
+ stub_request(:get, "https://order-url/item").
58
+ to_return(:status => 200, :body => '{"gui":{"snippet": "snippet-code"}}')
59
+
60
+ order.fetch
61
+ expect(order["gui"]["snippet"]).to eq('snippet-code')
62
+
63
+ end
64
+
65
+
66
+ end
67
+
68
+ end
@@ -0,0 +1,108 @@
1
+ require 'spec_helper'
2
+
3
+ describe KcoRuby::Order do
4
+ context "with mock connector" do
5
+ let(:connector) { instance_double(KcoRuby::Connector) }
6
+ subject { KcoRuby::Order.new(connector) }
7
+
8
+ describe "#new" do
9
+ it "should set location if provided to constructor" do
10
+ order = KcoRuby::Order.new(connector, 'http://test-uri')
11
+ expect(order.location).to eq('http://test-uri')
12
+ end
13
+ end
14
+
15
+
16
+ describe "#content_type=" do
17
+ it 'should return class content type' do
18
+ KcoRuby::Order.content_type = "application/json"
19
+ expect(subject.content_type).to eq("application/json")
20
+ end
21
+ end
22
+
23
+ describe "#location" do
24
+ it 'should return empty location' do
25
+ expect(subject.location).to be_nil
26
+ end
27
+
28
+ it 'should be able to set location' do
29
+ url = "http://foo"
30
+ subject.location = url
31
+ expect(subject.location).to eq(url)
32
+ end
33
+
34
+ it 'should allways return string' do
35
+ url = 5
36
+ subject.location = url
37
+ expect(subject.location).to be_instance_of(String)
38
+ end
39
+
40
+ end
41
+
42
+ describe "#parse and #marshal" do
43
+ it 'should parse and marshal identical' do
44
+ data = {"foo" => "boo"}
45
+ subject.parse(data)
46
+ expect(subject.marshal).to eq(data)
47
+ end
48
+ end
49
+
50
+ describe "#[](key)" do
51
+ it 'should return data for key' do
52
+ subject['key'] = "value"
53
+ expect(subject['key']).to eq("value")
54
+ end
55
+ end
56
+
57
+ describe "#[](key, value)=" do
58
+ it 'should ignore if using string or symbols' do
59
+ subject[:key] = "value"
60
+ expect(subject['key']).to eq("value")
61
+ end
62
+ end
63
+
64
+ describe "#keys" do
65
+ it 'should return all keys' do
66
+ subject["key1"] = "value1"
67
+ subject["key2"] = "value2"
68
+ expect(subject.keys).to contain_exactly("key1", "key2")
69
+ end
70
+ end
71
+
72
+ describe "#create" do
73
+ it 'should call connector#apply on #create' do
74
+ location = "http://stub"
75
+ subject.class.base_uri = location
76
+ data ={"foo" => "boo"}
77
+
78
+ expect(connector).to receive(:apply).with(:post, subject, {"url" => location, "data" => data})
79
+ subject.create(data)
80
+ end
81
+ end
82
+
83
+ describe "#fetch" do
84
+ it 'should call connector#apply with GET, subject and option' do
85
+ location = "http://stub"
86
+ subject.location = location
87
+ expect(connector).to receive(:apply).with(:get, subject, {"url" => location})
88
+ subject.fetch
89
+ end
90
+ end
91
+
92
+ describe "#update" do
93
+ it 'should call connector#apply with POST, subject and options' do
94
+ location = "http://klarna.com/foo/bar/13"
95
+ subject.location = location
96
+ data ={"foo" => "boo"}
97
+
98
+ expect(connector).to receive(:apply).with(:post, subject, {"url" => location, "data" => data})
99
+ subject.update(data)
100
+ end
101
+ end
102
+
103
+ it 'should contain zero keys' do
104
+ expect(subject.count).to eq(0)
105
+ end
106
+
107
+ end
108
+ end
@@ -0,0 +1,22 @@
1
+ require 'spec_helper'
2
+
3
+ describe KcoRuby::UserAgentField do
4
+ describe "#to_s" do
5
+ context "With options" do
6
+ subject { KcoRuby::UserAgentField.new('Test', 'name', 'version', [1, 2]) }
7
+ it "it serializes correctly" do
8
+ expected = "Test/name_version (1 ; 2)"
9
+ expect(subject.to_s).to eq(expected)
10
+ end
11
+ end
12
+
13
+ context "Without options" do
14
+ subject { KcoRuby::UserAgentField.new('Test', 'name', 'version') }
15
+ it "it serializes correctly without options" do
16
+ expected = "Test/name_version"
17
+ expect(subject.to_s).to eq(expected)
18
+ end
19
+ end
20
+ end
21
+
22
+ end
@@ -0,0 +1,28 @@
1
+ require 'spec_helper'
2
+
3
+ describe KcoRuby::UserAgent do
4
+
5
+ describe "#to_s" do
6
+ it 'should contain OS version' do
7
+ expect(subject.to_s).to match(/OS\/[^\ ]+_[^\ ]+/)
8
+ end
9
+
10
+ it 'should contain Library version' do
11
+ expect(subject.to_s).to match(/Library\/[^\ ]+_[^\ ]+/)
12
+ end
13
+
14
+ it 'should contain OS version' do
15
+ expect(subject.to_s).to match(/Language\/[^\ ]+_[^\ ]+/)
16
+ end
17
+ end
18
+
19
+ describe "#add_field" do
20
+ it 'should add field to fields' do
21
+ field = KcoRuby::UserAgentField.new("Module",
22
+ "Magento",
23
+ "5.0", ["LanguagePack/7", "JsLib/2.0"])
24
+ subject.add_field(field)
25
+ expect(subject.to_s).to match(/Module\/Magento_5\.0 \(LanguagePack\/7 ; JsLib\/2\.0\)/)
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,12 @@
1
+ require 'bundler/setup'
2
+ Bundler.setup
3
+
4
+ require 'simplecov'
5
+ SimpleCov.start
6
+
7
+ require 'webmock/rspec'
8
+ require 'kco_ruby'
9
+
10
+ RSpec.configure do |config|
11
+
12
+ end
metadata ADDED
@@ -0,0 +1,163 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: kco_ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Peter Hagström
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-12-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: sys-uname
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.9'
20
+ - - ">"
21
+ - !ruby/object:Gem::Version
22
+ version: 0.9.1
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '0.9'
30
+ - - ">"
31
+ - !ruby/object:Gem::Version
32
+ version: 0.9.1
33
+ - !ruby/object:Gem::Dependency
34
+ name: bundler
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '1.6'
40
+ type: :development
41
+ prerelease: false
42
+ version_requirements: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '1.6'
47
+ - !ruby/object:Gem::Dependency
48
+ name: rake
49
+ requirement: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '10.3'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - "~>"
59
+ - !ruby/object:Gem::Version
60
+ version: '10.3'
61
+ - !ruby/object:Gem::Dependency
62
+ name: rspec
63
+ requirement: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - "~>"
66
+ - !ruby/object:Gem::Version
67
+ version: '3.1'
68
+ type: :development
69
+ prerelease: false
70
+ version_requirements: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - "~>"
73
+ - !ruby/object:Gem::Version
74
+ version: '3.1'
75
+ - !ruby/object:Gem::Dependency
76
+ name: webmock
77
+ requirement: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - "~>"
80
+ - !ruby/object:Gem::Version
81
+ version: '1.8'
82
+ type: :development
83
+ prerelease: false
84
+ version_requirements: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - "~>"
87
+ - !ruby/object:Gem::Version
88
+ version: '1.8'
89
+ - !ruby/object:Gem::Dependency
90
+ name: simplecov
91
+ requirement: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - "~>"
94
+ - !ruby/object:Gem::Version
95
+ version: '0.9'
96
+ type: :development
97
+ prerelease: false
98
+ version_requirements: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - "~>"
101
+ - !ruby/object:Gem::Version
102
+ version: '0.9'
103
+ description: Klarna Checkout library
104
+ email:
105
+ - peter@significantbit.se
106
+ executables: []
107
+ extensions: []
108
+ extra_rdoc_files: []
109
+ files:
110
+ - ".gitignore"
111
+ - Gemfile
112
+ - LICENSE
113
+ - README.md
114
+ - Rakefile
115
+ - example.rb
116
+ - kco_ruby.gemspec
117
+ - lib/kco_ruby.rb
118
+ - lib/kco_ruby/connector.rb
119
+ - lib/kco_ruby/digester.rb
120
+ - lib/kco_ruby/order.rb
121
+ - lib/kco_ruby/request_context.rb
122
+ - lib/kco_ruby/response_handler.rb
123
+ - lib/kco_ruby/user_agent.rb
124
+ - lib/kco_ruby/version.rb
125
+ - spec/classes/connector_spec.rb
126
+ - spec/classes/digester_spec.rb
127
+ - spec/classes/example_spec.rb
128
+ - spec/classes/order_spec.rb
129
+ - spec/classes/user_agent_field_spec.rb
130
+ - spec/classes/user_agent_spec.rb
131
+ - spec/spec_helper.rb
132
+ homepage: https://github.com/significantbit/kco_ruby
133
+ licenses:
134
+ - Apache 2
135
+ metadata: {}
136
+ post_install_message:
137
+ rdoc_options: []
138
+ require_paths:
139
+ - lib
140
+ required_ruby_version: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ required_rubygems_version: !ruby/object:Gem::Requirement
146
+ requirements:
147
+ - - ">="
148
+ - !ruby/object:Gem::Version
149
+ version: '0'
150
+ requirements: []
151
+ rubyforge_project:
152
+ rubygems_version: 2.2.2
153
+ signing_key:
154
+ specification_version: 4
155
+ summary: A port of Klarna Checkout API to Ruby
156
+ test_files:
157
+ - spec/classes/connector_spec.rb
158
+ - spec/classes/digester_spec.rb
159
+ - spec/classes/example_spec.rb
160
+ - spec/classes/order_spec.rb
161
+ - spec/classes/user_agent_field_spec.rb
162
+ - spec/classes/user_agent_spec.rb
163
+ - spec/spec_helper.rb