Class: PayPal::SDK::Core::API::REST

Inherits:
Base
  • Object
show all
Defined in:
lib/paypal-sdk/core/api/rest.rb

Direct Known Subclasses

REST::API

Constant Summary collapse

NVP_AUTH_HEADER =
{
  :sandbox_email_address => "X-PAYPAL-SANDBOX-EMAIL-ADDRESS",
  :device_ipaddress      => "X-PAYPAL-DEVICE-IPADDRESS"
}
DEFAULT_HTTP_HEADER =
{
  "Content-Type" => "application/json"
}
DEFAULT_REST_END_POINTS =
{
  :sandbox => "https://api.sandbox.paypal.com",
  :live    => "https://api.paypal.com",
}
TOKEN_REQUEST_PARAMS =
"grant_type=client_credentials"

Constants inherited from Base

Base::API_MODES, Base::DEFAULT_API_MODE

Instance Attribute Summary collapse

Attributes inherited from Base

#http, #service_name, #uri

Instance Method Summary collapse

Methods inherited from Base

#api_mode, #default_http_header, #delete, #format_error, #get, #initialize, #patch, #post, #put, sdk_library_details, user_agent

Methods included from Util::HTTPHelper

#configure_ssl, #create_http_connection, #default_ca_file, #encode_www_form, #http_call, #map_header_value, #new_http, #url_join

Methods included from PayPal::SDK::Core::Authentication

#add_certificate, #base_credential, #base_credential_type, #credential, #third_party_credential

Methods included from Configuration

#config

Methods included from Logging

#log_event, #logger, logger, logger=

Constructor Details

This class inherits a constructor from PayPal::SDK::Core::API::Base

Instance Attribute Details

#token_hash(auth_code = nil, headers = nil) ⇒ Object

Generate Oauth token or Get cached



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/paypal-sdk/core/api/rest.rb', line 48

def token_hash(auth_code=nil, headers=nil)
  validate_token_hash
  @token_hash ||=
    begin
      @token_request_at = Time.now
      basic_auth = ["#{config.client_id}:#{config.client_secret}"].pack('m').delete("\r\n")
      token_headers = default_http_header.merge({
        "Content-Type"  => "application/x-www-form-urlencoded",
        "Authorization" => "Basic #{basic_auth}" }).merge(headers)
      if auth_code != nil
        TOKEN_REQUEST_PARAMS.replace "grant_type=authorization_code&response_type=token&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&code="
        TOKEN_REQUEST_PARAMS << auth_code
      end
      response = http_call( :method => :post, :uri => token_uri, :body => TOKEN_REQUEST_PARAMS, :header => token_headers )
      MultiJson.load(response.body, :symbolize_keys => true)
    end
end

Instance Method Details

#api_call(payload) ⇒ Object

Override the API call to handle Token Expire



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/paypal-sdk/core/api/rest.rb', line 92

def api_call(payload)
  backup_payload  = payload.dup
  begin
    response = super(payload)
  rescue UnauthorizedAccess => error
    if @token_hash and config.client_id
      # Reset cached token and Retry api request
      @token_hash = nil
      response = super(backup_payload)
    else
      raise error
    end
  end
  response
end

#flat_hash(h) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
# File 'lib/paypal-sdk/core/api/rest.rb', line 155

def flat_hash(h)
  new_hash = {}
  h.each_pair do |key, val|
    if val.is_a?(Hash)
      new_hash.merge!(flat_hash(val))
    else
      new_hash[key] = val
    end
  end
  new_hash
end

#format_request(payload) ⇒ Object

Format request payload

Argument

  • payload( uri, action, params, header)

Generate

  • payload( uri, body, header )



121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/paypal-sdk/core/api/rest.rb', line 121

def format_request(payload)
  # Request URI
  payload[:uri].path = url_join(payload[:uri].path, payload[:action])
  # HTTP Header
  credential_properties = credential(payload[:uri].to_s).properties
  header = map_header_value(NVP_AUTH_HEADER, credential_properties)
  payload[:header]  = header.merge("Authorization" => "#{token_type(payload[:header])} #{token(nil, payload[:header])}").
    merge(DEFAULT_HTTP_HEADER).merge(payload[:header])
  # Post Data
  payload[:body]    = MultiJson.dump(payload[:params])
  payload
end

#format_response(payload) ⇒ Object

Format response payload

Argument

  • payload( response )

Generate

  • payload( data )



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/paypal-sdk/core/api/rest.rb', line 139

def format_response(payload)
  response = payload[:response]
  payload[:data] =
    if response.body && response.body.strip == ""
      {}
    elsif response.code >= "200" and response.code <= "299"
      response.body && response.content_type == "application/json" ? MultiJson.load(response.body) : {}
    elsif response.content_type == "application/json"
      { "error" => flat_hash(MultiJson.load(response.body)) }
    else
      { "error" => { "name" => response.code, "message" => response.message,
        "developer_msg" => response } }
    end
  payload
end

#handle_response(response) ⇒ Object

Validate HTTP response



109
110
111
112
113
114
# File 'lib/paypal-sdk/core/api/rest.rb', line 109

def handle_response(response)
  super
rescue BadRequest => error
  # Catch BadRequest to get validation error message from the response.
  error.response
end

#log_http_call(payload) ⇒ Object

Log PayPal-Request-Id header



168
169
170
171
172
173
# File 'lib/paypal-sdk/core/api/rest.rb', line 168

def log_http_call(payload)
  if payload[:header] and payload[:header]["PayPal-Request-Id"]
    logger.info "PayPal-Request-Id: #{payload[:header]["PayPal-Request-Id"]}"
  end
  super
end

#service_endpointObject

Get REST service end point



21
22
23
# File 'lib/paypal-sdk/core/api/rest.rb', line 21

def service_endpoint
  config.rest_endpoint || super || DEFAULT_REST_END_POINTS[api_mode]
end

#set_config(*args) ⇒ Object

Clear cached values.



31
32
33
34
35
# File 'lib/paypal-sdk/core/api/rest.rb', line 31

def set_config(*args)
  @token_uri = nil
  @token_hash = nil
  super
end

#token(auth_code = nil, headers = {}) ⇒ Object

Get access token



68
69
70
# File 'lib/paypal-sdk/core/api/rest.rb', line 68

def token(auth_code=nil, headers={})
  token_hash(auth_code, headers)[:access_token]
end

#token=(new_token) ⇒ Object

token setter



78
79
80
# File 'lib/paypal-sdk/core/api/rest.rb', line 78

def token=(new_token)
  @token_hash = { :access_token => new_token, :token_type => "Bearer" }
end

#token_endpointObject

Token endpoint



26
27
28
# File 'lib/paypal-sdk/core/api/rest.rb', line 26

def token_endpoint
  config.rest_token_endpoint || service_endpoint
end

#token_type(headers = {}) ⇒ Object

Get access token type



73
74
75
# File 'lib/paypal-sdk/core/api/rest.rb', line 73

def token_type(headers={})
  token_hash(nil, headers)[:token_type] || "Bearer"
end

#token_uriObject

URI object token endpoint



38
39
40
41
42
43
44
45
# File 'lib/paypal-sdk/core/api/rest.rb', line 38

def token_uri
  @token_uri ||=
    begin
      new_uri = URI.parse(token_endpoint)
      new_uri.path = "/v1/oauth2/token" if new_uri.path =~ /^\/?$/
      new_uri
    end
end

#validate_token_hashObject

Check token expired or not



83
84
85
86
87
88
89
# File 'lib/paypal-sdk/core/api/rest.rb', line 83

def validate_token_hash
  if @token_request_at and
      @token_hash and @token_hash[:expires_in] and
      (Time.now - @token_request_at) > @token_hash[:expires_in].to_i
    @token_hash = nil
  end
end