wepay_client 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,6 @@
1
+ *.gem
2
+ .bundle
3
+ Gemfile.lock
4
+ pkg/*
5
+ .idea
6
+ .rvmrc
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "http://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in wepay_client.gemspec
4
+ gemspec
data/README ADDED
@@ -0,0 +1,24 @@
1
+ This is a simple ruby client to interact with wepay apis.
2
+
3
+ Usage
4
+
5
+ In rails put following in Gemfile
6
+ gem 'wepay_client',:git => 'git://github.com/amitrawal/wepay_client.git'
7
+
8
+ Create a wepay_config.rb in config/initializers folder and setup the client with wepay client id and client secret
9
+
10
+ require 'wepay_client'
11
+
12
+ WepayClient::Client.configure do
13
+ client_id '11111111'
14
+ client_secret '5f434343'
15
+ use_ssl true
16
+ use_stage !(ENV['RAILS_ENV'] == 'production')
17
+ end
18
+
19
+
20
+ example to call wepay apis
21
+
22
+ wepay = WepayClient::Client.instance
23
+ account = wepay.create_account('token data', 1122334)
24
+ p account[:account_id]
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
@@ -0,0 +1,27 @@
1
+ module WepayClient
2
+ class Client
3
+ def create_account(access_token, params = {})
4
+ self.post("/account/create", access_token, params)
5
+ end
6
+
7
+ def get_account(access_token, account_id)
8
+ self.post("/account", access_token, {:account_id => account_id})
9
+ end
10
+
11
+ def find_account(access_token, params = {})
12
+ self.post("/account/find", access_token, params)
13
+ end
14
+
15
+ def modify_account(access_token, account_id, params={})
16
+ self.post("/account/modify", access_token, params.merge({:account_id => account_id}))
17
+ end
18
+
19
+ def delete_account(access_token, account_id)
20
+ self.post("/account/delete", access_token, {:account_id => account_id})
21
+ end
22
+
23
+ def get_account_balance(access_token, account_id)
24
+ self.post("/account/balance", access_token, {:account_id => account_id})
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,23 @@
1
+ module WepayClient
2
+ class Client
3
+ def get_checkout(access_token, checkout_id)
4
+ self.post("/checkout", access_token, {:checkout_id => checkout_id})
5
+ end
6
+
7
+ def create_checkout(access_token, params = {})
8
+ defaults = {
9
+ :fee_payer => 'Payee',
10
+ :type => 'SERVICE',
11
+ :charge_tax => 0,
12
+ :app_fee => 0,
13
+ :auto_capture => 1,
14
+ :require_shipping => 0
15
+ }.merge(params)
16
+ self.post("/checkout/create", access_token, defaults.merge(params))
17
+ end
18
+
19
+ def refund(access_token, checkout_id, params = {})
20
+ self.post("/checkout/refund", access_token, params.merge(:checkout_id => checkout_id))
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,140 @@
1
+ require 'net/http'
2
+ require 'net/https'
3
+ require 'uri'
4
+ require 'json'
5
+ require 'cgi'
6
+ require 'singleton'
7
+ require 'active_support' # String conversions
8
+
9
+ module WepayClient
10
+ class Client
11
+ include Singleton
12
+
13
+ STAGE_API_ENDPOINT = "https://stage.wepayapi.com/v2"
14
+ STAGE_UI_ENDPOINT = "https://stage.wepay.com/v2"
15
+
16
+ PRODUCTION_API_ENDPOINT = "https://wepayapi.com/v2"
17
+ PRODUCTION_UI_ENDPOINT = "https://www.wepay.com/v2"
18
+
19
+ CLIENT_ID = '123456'
20
+ CLIENT_SECRET = '123456'
21
+
22
+ def self.configure(&blk)
23
+ self.instance.configure &blk
24
+ end
25
+
26
+ # Simple DSL to configure the client.
27
+ def configure(&blk)
28
+ instance_eval &blk
29
+ end
30
+
31
+ def api_endpoint
32
+ if @use_stage
33
+ STAGE_API_ENDPOINT
34
+ else
35
+ PRODUCTION_API_ENDPOINT
36
+ end
37
+ end
38
+
39
+ def ui_endpoint
40
+ if @use_stage
41
+ STAGE_UI_ENDPOINT
42
+ else
43
+ PRODUCTION_UI_ENDPOINT
44
+ end
45
+ end
46
+
47
+ def use_stage(_use_stage = nil)
48
+ @use_stage = _use_stage if _use_stage
49
+ @use_stage
50
+ end
51
+
52
+ def use_ssl(_use_ssl = nil)
53
+ @use_stage = _use_ssl if _use_ssl
54
+ @use_stage
55
+ end
56
+
57
+ def client_secret(secret = nil)
58
+ @client_secret = secret if secret
59
+ @client_secret
60
+ end
61
+
62
+ def client_id(_client_id = nil)
63
+ @client_id = _client_id if _client_id
64
+ @client_id
65
+ end
66
+
67
+ # this function returns the URL that you send the user to to authorize your API application
68
+ # the redirect_uri must be a full uri (ex https://www.wepay.com)
69
+ def auth_code_url(redirect_uri, user_email = false, user_name = false, permissions = "manage_accounts,view_balance,collect_payments,refund_payments,view_user,preapprove_payments")
70
+ url = ui_endpoint + '/oauth2/authorize?client_id=' + client_id.to_s + '&redirect_uri=' + redirect_uri + '&scope=' + permissions
71
+ url += user_name ? '&user_name=' + CGI::escape(user_name) : ''
72
+ url += user_email ? '&user_email=' + CGI::escape(user_email) : ''
73
+ end
74
+
75
+ # this function will make a call to the /v2/oauth2/token endpoint to exchange a code for an access_token
76
+ def get_access_token(auth_code, redirect_uri)
77
+ json = post('/oauth2/token', nil, {'client_id' => client_id, 'client_secret' => client_secret, 'redirect_uri' => redirect_uri, 'code' => auth_code })
78
+ raise WepayClient::Exceptions::AccessTokenError.new("A problem occurred trying to get the access token: #{json.inspect}") unless json.has_key?(:access_token)
79
+ json[:access_token]
80
+ end
81
+
82
+ protected
83
+
84
+ def request(type, endpoint, access_token, body = nil)
85
+ uri = URI.parse(api_endpoint + endpoint)
86
+ http = Net::HTTP.new(uri.host, uri.port)
87
+ http.use_ssl = use_ssl
88
+
89
+ # construct the call data and access token
90
+ req = Net::HTTP.const_get(type.to_s.camelize).new(uri.request_uri, initheader = {'Content-Type' =>'application/json', 'User-Agent' => 'WePay Ruby SDK'})
91
+ req.add_field('Authorization: Bearer', access_token) if access_token
92
+ req.body = body.to_json if body
93
+ http.request(req)
94
+ end
95
+
96
+ def post(endpoint, access_token, params)
97
+ res = request(:post, endpoint, access_token, params)
98
+ handle_response res
99
+ end
100
+
101
+ def handle_response(response)
102
+ begin
103
+ json = symbolize_response(response.body)
104
+ rescue Errno, JSON::ParserError => e
105
+ raise WepayClient::Exceptions::WepayApiError.new("The request to WePay timed out. This might mean you sent an invalid request or WePay is having issues.")
106
+ rescue => e
107
+ raise e if e.class.to_s =~ /WepayClient/
108
+ raise WepayClient::Exceptions::WepayApiError.new("There was an error while trying to connect with WePay - #{e.inspect}")
109
+ end
110
+ if response.kind_of?(Net::HTTPSuccess)
111
+ return json
112
+ elsif response.code == 401
113
+ raise WepayClient::Exceptions::ExpiredTokenError.new("Token either expired, revoked or invalid: #{json.inspect}.")
114
+ else
115
+ raise WepayClient::Exceptions::WepayApiError.new("The API request failed with error code ##{response.code}: #{json.inspect}.")
116
+ end
117
+ end
118
+
119
+ def symbolize_response(response)
120
+ json = JSON.parse(response)
121
+ if json.kind_of? Hash
122
+ json.symbolize_keys! and raise_if_response_error(json)
123
+ elsif json.kind_of? Array
124
+ json.each{|h| h.symbolize_keys!}
125
+ end
126
+ json
127
+ end
128
+
129
+ def raise_if_response_error(json)
130
+ if json.has_key?(:error) && json.has_key?(:error_description)
131
+ if ['invalid code parameter','the code has expired','this access_token has been revoked', 'a valid access_token is required'].include?(json[:error_description])
132
+ raise WepayClient::Exceptions::ExpiredTokenError.new("Token either expired, revoked or invalid: #{json[:error_description]}")
133
+ else
134
+ raise WepayClient::Exceptions::WepayApiError.new(json[:error_description])
135
+ end
136
+ end
137
+ end
138
+
139
+ end
140
+ end
@@ -0,0 +1,10 @@
1
+ module WepayClient
2
+ module Exceptions
3
+ class AccessTokenError < StandardError; end
4
+ class ExpiredTokenError < StandardError; end
5
+ class InitializeCheckoutError < StandardError; end
6
+ class AuthorizationError < StandardError; end
7
+ class WepayCheckoutError < StandardError; end
8
+ class WepayApiError < StandardError; end
9
+ end
10
+ end
@@ -0,0 +1,30 @@
1
+ module WepayClient
2
+ class Client
3
+ PREAPPROVAL_PERIODS = {
4
+ :hourly => 'hourly',
5
+ :daily => 'daily',
6
+ :weekly => 'weekly',
7
+ :biweekly => 'biweekly',
8
+ :monthly => 'monthly',
9
+ :quarterly=> 'quarterly',
10
+ :yearly => 'yearly',
11
+ :once => 'once'
12
+ }
13
+
14
+ def create_preapproval(access_token, params = {})
15
+ defaults = {
16
+ :frequency => 10
17
+ }.merge(params)
18
+
19
+ self.post("/preapproval/create", access_token, defaults)
20
+ end
21
+
22
+ def get_preapproval(access_token, preapproval_id)
23
+ self.post("/preapproval", access_token, {:preapproval_id => preapproval_id})
24
+ end
25
+
26
+ def cancel_preapproval(access_token, preapproval_id)
27
+ self.post("/preapproval/cancel", access_token, {:preapproval_id => preapproval_id})
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,3 @@
1
+ module WepayClient
2
+ VERSION = "0.0.3"
3
+ end
@@ -0,0 +1,8 @@
1
+ require 'wepay_client/version'
2
+ require 'wepay_client/client'
3
+ require 'wepay_client/account'
4
+ require 'wepay_client/checkout'
5
+ require 'wepay_client/preapproval'
6
+ require 'wepay_client/exceptions'
7
+
8
+
@@ -0,0 +1,38 @@
1
+ require 'spec/spec_helper'
2
+
3
+ describe 'WepayClient::Client' do
4
+ before(:all) do
5
+ configure_client
6
+ @client = WepayClient::Client.instance
7
+ end
8
+
9
+ it 'should return proper auth_code_url' do
10
+ url = @client.auth_code_url 'http://test.com'
11
+ url.should_not be_nil
12
+ end
13
+
14
+ it 'should return access_token on get_access_token' do
15
+ return_json_for_api_request response_for_access_token
16
+ access_token = @client.get_access_token '123456', 'http://test.com'
17
+ access_token.should_not be_nil
18
+ end
19
+
20
+ it 'should raise AccessTokenError exception if access_token is not return by get_access_token' do
21
+ return_json_for_api_request "{}"
22
+ lambda { @client.get_access_token '123456', 'http://test.com' }.should raise_error(WepayClient::Exceptions::AccessTokenError)
23
+ end
24
+
25
+ it 'should create an account on create_account' do
26
+ return_json_for_api_request response_for_create_account
27
+
28
+ account_resp = @client.create_account '123456',{
29
+ "name" => "Example Account",
30
+ "description" => "This is just an example WePay account.",
31
+ "reference_id" => "abc123",
32
+ "image_uri" => "https://stage.wepay.com/img/logo.png"
33
+ }
34
+
35
+ account_resp.should_not be_nil
36
+ account_resp[:account_id].should_not be_nil
37
+ end
38
+ end
@@ -0,0 +1,9 @@
1
+ module ConfigHelper
2
+ def configure_client
3
+ WepayClient::Client.configure do
4
+ client_id WepayClient::Client::CLIENT_ID
5
+ client_secret WepayClient::Client::CLIENT_SECRET
6
+ use_ssl true
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,5 @@
1
+ module MockHelper
2
+ def return_json_for_api_request(body, is_success = true)
3
+ WepayClient::Client.instance.stub(:request => mock({:body => body, 'success?' => is_success}))
4
+ end
5
+ end
@@ -0,0 +1,15 @@
1
+ module WepayResponse
2
+ def response_for_access_token
3
+ load_resp 'access_token_success.json'
4
+ end
5
+
6
+ def response_for_create_account
7
+ load_resp 'account_creation_success.json'
8
+ end
9
+
10
+ def load_resp(file_name)
11
+ file_path = File.expand_path("../../wepay_response/#{file_name}", __FILE__)
12
+ json = File.open(file_path, "r").read
13
+ json
14
+ end
15
+ end
@@ -0,0 +1,21 @@
1
+ require 'rubygems'
2
+ require 'bundler/setup'
3
+ require 'wepay_client'
4
+
5
+ # Requires supporting ruby files with custom matchers and macros, etc,
6
+ # in spec/support/ and its subdirectories.
7
+ Dir[File.join(File.dirname(__FILE__), 'helpers/*.rb')].each {|f| require f}
8
+
9
+ RSpec.configure do |config|
10
+ # ## Mock Framework
11
+ #
12
+ # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
13
+ #
14
+ #config.mock_with :mocha
15
+ # config.mock_with :flexmock
16
+ # config.mock_with :rr
17
+
18
+ config.include MockHelper
19
+ config.include ConfigHelper
20
+ config.include WepayResponse
21
+ end
@@ -0,0 +1,5 @@
1
+ {
2
+ "user_id":12345,
3
+ "access_token":"5220ba86b6c4cbaf6a78ccf60dfe83514eeb8b1ee88f1a58f9de7d818f68",
4
+ "token_type":"BEARER"
5
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "account_id":12345,
3
+ "account_uri":"https://stage.wepay.com/account/12345"
4
+ }
@@ -0,0 +1,24 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "wepay_client/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "wepay_client"
7
+ s.version = WepayClient::VERSION
8
+ s.authors = ["Amit Rawal"]
9
+ s.email = ["amit.rawal@in.v2solutions.com"]
10
+ s.homepage = ""
11
+ s.summary = %q{Wepay client gem}
12
+ s.description = %q{Simple wrapper around wepay's api'}
13
+
14
+ s.rubyforge_project = "wepay_client"
15
+
16
+ s.files = `git ls-files`.split("\n")
17
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
19
+ s.require_paths = ["lib"]
20
+
21
+ s.add_dependency 'json'
22
+ s.add_development_dependency "rspec"
23
+ s.add_runtime_dependency "activesupport", '~> 2'
24
+ end
metadata ADDED
@@ -0,0 +1,125 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: wepay_client
3
+ version: !ruby/object:Gem::Version
4
+ hash: 25
5
+ prerelease:
6
+ segments:
7
+ - 0
8
+ - 0
9
+ - 3
10
+ version: 0.0.3
11
+ platform: ruby
12
+ authors:
13
+ - Amit Rawal
14
+ autorequire:
15
+ bindir: bin
16
+ cert_chain: []
17
+
18
+ date: 2012-11-26 00:00:00 Z
19
+ dependencies:
20
+ - !ruby/object:Gem::Dependency
21
+ name: json
22
+ prerelease: false
23
+ requirement: &id001 !ruby/object:Gem::Requirement
24
+ none: false
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ hash: 3
29
+ segments:
30
+ - 0
31
+ version: "0"
32
+ type: :runtime
33
+ version_requirements: *id001
34
+ - !ruby/object:Gem::Dependency
35
+ name: rspec
36
+ prerelease: false
37
+ requirement: &id002 !ruby/object:Gem::Requirement
38
+ none: false
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ hash: 3
43
+ segments:
44
+ - 0
45
+ version: "0"
46
+ type: :development
47
+ version_requirements: *id002
48
+ - !ruby/object:Gem::Dependency
49
+ name: activesupport
50
+ prerelease: false
51
+ requirement: &id003 !ruby/object:Gem::Requirement
52
+ none: false
53
+ requirements:
54
+ - - ~>
55
+ - !ruby/object:Gem::Version
56
+ hash: 7
57
+ segments:
58
+ - 2
59
+ version: "2"
60
+ type: :runtime
61
+ version_requirements: *id003
62
+ description: Simple wrapper around wepay's api'
63
+ email:
64
+ - amit.rawal@in.v2solutions.com
65
+ executables: []
66
+
67
+ extensions: []
68
+
69
+ extra_rdoc_files: []
70
+
71
+ files:
72
+ - .gitignore
73
+ - Gemfile
74
+ - README
75
+ - Rakefile
76
+ - lib/wepay_client.rb
77
+ - lib/wepay_client/account.rb
78
+ - lib/wepay_client/checkout.rb
79
+ - lib/wepay_client/client.rb
80
+ - lib/wepay_client/exceptions.rb
81
+ - lib/wepay_client/preapproval.rb
82
+ - lib/wepay_client/version.rb
83
+ - spec/client_spec.rb
84
+ - spec/helpers/config_helper.rb
85
+ - spec/helpers/mock_helper.rb
86
+ - spec/helpers/wepay_response.rb
87
+ - spec/spec_helper.rb
88
+ - spec/wepay_response/access_token_success.json
89
+ - spec/wepay_response/account_creation_success.json
90
+ - wepay_client.gemspec
91
+ homepage: ""
92
+ licenses: []
93
+
94
+ post_install_message:
95
+ rdoc_options: []
96
+
97
+ require_paths:
98
+ - lib
99
+ required_ruby_version: !ruby/object:Gem::Requirement
100
+ none: false
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ hash: 3
105
+ segments:
106
+ - 0
107
+ version: "0"
108
+ required_rubygems_version: !ruby/object:Gem::Requirement
109
+ none: false
110
+ requirements:
111
+ - - ">="
112
+ - !ruby/object:Gem::Version
113
+ hash: 3
114
+ segments:
115
+ - 0
116
+ version: "0"
117
+ requirements: []
118
+
119
+ rubyforge_project: wepay_client
120
+ rubygems_version: 1.8.24
121
+ signing_key:
122
+ specification_version: 3
123
+ summary: Wepay client gem
124
+ test_files: []
125
+