Class: GoCardless::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/gocardless/client.rb

Constant Summary collapse

BASE_URLS =
{
  :production => 'https://gocardless.com',
  :sandbox    => 'https://sandbox.gocardless.com',
}
API_PATH =
'/api/v1'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Client

Returns a new instance of Client.

Raises:



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/gocardless/client.rb', line 32

def initialize(args = {})
  Utils.symbolize_keys! args
  @app_id = args[:app_id]
  @app_secret = args[:app_secret]
  raise ClientError.new("You must provide an app_id") unless @app_id
  raise ClientError.new("You must provide an app_secret") unless @app_secret

  @oauth_client = OAuth2::Client.new(@app_id, @app_secret,
                                     :site => self.class.base_url,
                                     :token_url => '/oauth/access_token')

  self.access_token = args[:token] if args[:token]
  @merchant_id = args[:merchant_id] if args[:merchant_id]
end

Class Method Details

.api_url ⇒ Object



27
28
29
# File 'lib/gocardless/client.rb', line 27

def api_url
  "#{base_url}#{API_PATH}"
end

.base_url ⇒ Object



23
24
25
# File 'lib/gocardless/client.rb', line 23

def base_url
  @base_url || BASE_URLS[GoCardless.environment || :production]
end

.base_url=(url) ⇒ Object



19
20
21
# File 'lib/gocardless/client.rb', line 19

def base_url=(url)
  @base_url = url.sub(%r|/$|, '')
end

Instance Method Details

#access_token ⇒ String

Returns a serialized form of the access token with its scope.

Returns:

  • (String) —

    a serialized form of the access token with its scope



82
83
84
85
86
87
# File 'lib/gocardless/client.rb', line 82

def access_token
  if @access_token
    scope = @access_token.params[:scope] || @access_token.params['scope']
    "#{@access_token.token} #{scope}".strip
  end
end

#access_token=(token) ⇒ Object

Set the client's access token

Parameters:

  • token (String) —

    a string with format "#{token} #{scope}" (as returned by #access_token)



93
94
95
96
97
98
99
100
101
# File 'lib/gocardless/client.rb', line 93

def access_token=(token)
  token, scope = token.sub(/^bearer\s+/i, '').split(' ', 2)
  scope ||= ''

  @access_token = OAuth2::AccessToken.new(@oauth_client, token)
  @access_token.params['scope'] = scope

  set_merchant_id_from_scope(scope) unless @merchant_id
end

#api_get(path, params = {}) ⇒ Hash

Note:

this method is for internal use

Issue an GET request to the API server

Parameters:

  • path (String) —

    the path that will be added to the API prefix

  • params (Hash) (defaults to: {}) —

    query string parameters

Returns:

  • (Hash) —

    hash the parsed response data



109
110
111
# File 'lib/gocardless/client.rb', line 109

def api_get(path, params = {})
  request(:get, "#{API_PATH}#{path}", :params => params).parsed
end

#api_post(path, data = {}) ⇒ Hash

Note:

this method is for internal use

Issue a POST request to the API server

Parameters:

  • path (String) —

    the path that will be added to the API prefix

  • data (Hash) (defaults to: {}) —

    a hash of data that will be sent as the request body

Returns:

  • (Hash) —

    hash the parsed response data



119
120
121
# File 'lib/gocardless/client.rb', line 119

def api_post(path, data = {})
  request(:post, "#{API_PATH}#{path}", :data => data).parsed
end

#api_put(path, data = {}) ⇒ Hash

Note:

this method is for internal use

Issue a PUT request to the API server

Parameters:

  • path (String) —

    the path that will be added to the API prefix

  • data (Hash) (defaults to: {}) —

    a hash of data that will be sent as the request body

Returns:

  • (Hash) —

    hash the parsed response data



129
130
131
# File 'lib/gocardless/client.rb', line 129

def api_put(path, data = {})
  request(:put, "#{API_PATH}#{path}", :data => data).parsed
end

#authorize_url(options) ⇒ String Also known as: new_merchant_url

Generate the OAuth authorize url

Parameters:

  • options (Hash) —

    parameters to be included in the url. :redirect_uri is required.

Returns:

  • (String) —

    the authorize url

Raises:

  • (ArgumentError)


52
53
54
55
56
57
58
59
60
61
62
# File 'lib/gocardless/client.rb', line 52

def authorize_url(options)
  raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri]
  params = {
    :client_id => @app_id,
    :response_type => 'code',
    :scope => 'manage_merchant'
  }
  # Faraday doesn't flatten params in this case (Faraday issue #115)
  options = Hash[Utils.flatten_params(options)]
  @oauth_client.authorize_url(params.merge(options))
end

#bill(id) ⇒ Bill

Returns the Bill matching the id requested.

Parameters:

  • id (String) —

    of the bill

Returns:

  • (Bill) —

    the Bill matching the id requested



164
165
166
# File 'lib/gocardless/client.rb', line 164

def bill(id)
  Bill.find_with_client(self, id)
end

#confirm_resource(params) ⇒ Resource

Confirm a newly-created subscription, pre-authorzation or one-off payment. This method also checks that the resource response data includes a valid signature and will raise a SignatureError if the signature is invalid.

Parameters:

  • params (Hash) —

    the response parameters returned by the API server

Returns:

  • (Resource) —

    the confirmed resource object



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/gocardless/client.rb', line 227

def confirm_resource(params)
  params = prepare_params(params)

  if signature_valid?(params)
    data = {
      :resource_id => params[:resource_id],
      :resource_type => params[:resource_type],
    }

    credentials = Base64.encode64("#{@app_id}:#{@app_secret}")
    credentials = credentials.gsub(/\s/, '')
    headers = {
      'Authorization' => "Basic #{credentials}"
    }
    request(:post, "#{self.class.api_url}/confirm", :data => data,
                                                    :headers => headers)

    # Initialize the correct class according to the resource's type
    klass = GoCardless.const_get(Utils.camelize(params[:resource_type]))
    klass.find_with_client(self, params[:resource_id])
  else
    raise SignatureError, 'An invalid signature was detected'
  end
end

#create_bill(attrs) ⇒ Bill

Create a new bill under a given pre-authorization

Parameters:

  • attrs (Hash) —

    must include :pre_authorization_id and :amount

Returns:

  • (Bill) —

    the created bill object

See Also:



180
181
182
# File 'lib/gocardless/client.rb', line 180

def create_bill(attrs)
  Bill.new_with_client(self, attrs).save
end

#fetch_access_token(auth_code, options) ⇒ String

Exchange the authorization code for an access token

Parameters:

  • auth_code (String) —

    to exchange for the access_token

Returns:

  • (String) —

    the access_token required to make API calls to resources

Raises:

  • (ArgumentError)


69
70
71
72
73
74
75
76
77
78
79
# File 'lib/gocardless/client.rb', line 69

def fetch_access_token(auth_code, options)
  raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri]
  # Exchange the auth code for an access token
  @access_token = @oauth_client.auth_code.get_token(auth_code, options)

  # Use the scope to figure out which merchant we're managing
  scope = @access_token.params[:scope] || @access_token.params['scope']
  set_merchant_id_from_scope(scope)

  self.access_token
end

#merchant ⇒ Merchant

Returns the merchant associated with the client's access token.

Returns:

  • (Merchant) —

    the merchant associated with the client's access token

Raises:



135
136
137
138
# File 'lib/gocardless/client.rb', line 135

def merchant
  raise ClientError, 'Access token missing' unless @access_token
  Merchant.new_with_client(self, api_get("/merchants/#{merchant_id}"))
end

#new_bill_url(params) ⇒ String

Generate the URL for creating a new bill. The parameters passed in define various attributes of the bill. Redirecting a user to the resulting URL will show them a page where they can approve or reject the bill described by the parameters. Note that this method automatically includes the nonce, timestamp and signature.

Parameters:

  • params (Hash) —

    the bill parameters

Returns:

  • (String) —

    the generated URL



216
217
218
# File 'lib/gocardless/client.rb', line 216

def new_bill_url(params)
  new_limit_url(:bill, params)
end

#new_pre_authorization_url(params) ⇒ String

Generate the URL for creating a new pre authorization. The parameters passed in define various attributes of the pre authorization. Redirecting a user to the resulting URL will show them a page where they can approve or reject the pre authorization described by the parameters. Note that this method automatically includes the nonce, timestamp and signature.

Parameters:

  • params (Hash) —

    the pre authorization parameters

Returns:

  • (String) —

    the generated URL



204
205
206
# File 'lib/gocardless/client.rb', line 204

def new_pre_authorization_url(params)
  new_limit_url(:pre_authorization, params)
end

#new_subscription_url(params) ⇒ String

Generate the URL for creating a new subscription. The parameters passed in define various attributes of the subscription. Redirecting a user to the resulting URL will show them a page where they can approve or reject the subscription described by the parameters. Note that this method automatically includes the nonce, timestamp and signature.

Parameters:

  • params (Hash) —

    the subscription parameters

Returns:

  • (String) —

    the generated URL



192
193
194
# File 'lib/gocardless/client.rb', line 192

def new_subscription_url(params)
  new_limit_url(:subscription, params)
end

#payment(id) ⇒ Payment

Returns the payment matching the id requested.

Parameters:

  • id (String) —

    of the payment

Returns:

  • (Payment) —

    the payment matching the id requested



171
172
173
# File 'lib/gocardless/client.rb', line 171

def payment(id)
  Payment.find_with_client(self, id)
end

#pre_authorization(id) ⇒ PreAuthorization

Returns the pre_authorization matching the id requested.

Parameters:

  • id (String) —

    of the pre_authorization

Returns:



150
151
152
# File 'lib/gocardless/client.rb', line 150

def pre_authorization(id)
  PreAuthorization.find_with_client(self, id)
end

#response_params_valid?(params) ⇒ Boolean

Check that resource response data includes a valid signature.

Parameters:

  • params (Hash) —

    the response parameters returned by the API server

Returns:

  • (Boolean) —

    true when valid, false otherwise



257
258
259
260
261
# File 'lib/gocardless/client.rb', line 257

def response_params_valid?(params)
  params = prepare_params(params)

  signature_valid?(params)
end

#subscription(id) ⇒ Subscription

Returns the subscription matching the id requested.

Parameters:

  • id (String) —

    of the subscription

Returns:

  • (Subscription) —

    the subscription matching the id requested



143
144
145
# File 'lib/gocardless/client.rb', line 143

def subscription(id)
  Subscription.find_with_client(self, id)
end

#subscripton(id) ⇒ Subscription

Returns the subscription matching the id requested.

Parameters:

  • id (String) —

    of the subscription

Returns:

  • (Subscription) —

    the subscription matching the id requested



143
144
145
# File 'lib/gocardless/client.rb', line 143

def subscription(id)
  Subscription.find_with_client(self, id)
end

#user(id) ⇒ User

Returns the User matching the id requested.

Parameters:

  • id (String) —

    of the user

Returns:

  • (User) —

    the User matching the id requested



157
158
159
# File 'lib/gocardless/client.rb', line 157

def user(id)
  User.find_with_client(self, id)
end

#webhook_valid?(params) ⇒ Boolean

Validates the payload contents of a webhook request.

Parameters:

  • params (Hash) —

    the contents of payload of the webhook

Returns:

  • (Boolean) —

    true when valid, false otherwise



268
269
270
# File 'lib/gocardless/client.rb', line 268

def webhook_valid?(params)
  signature_valid?(params)
end