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

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

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_hashObject

Generate Oauth token or Get cached



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

def token_hash
  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}" })
      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



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/paypal-sdk/core/api/rest.rb', line 88

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

#format_request(payload) ⇒ Object

Format request payload

Argument

  • payload( uri, action, params, header)

Generate

  • payload( uri, body, header )



117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/paypal-sdk/core/api/rest.rb', line 117

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} #{token}").
    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 )



135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/paypal-sdk/core/api/rest.rb', line 135

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

#handle_response(response) ⇒ Object

Validate HTTP response



105
106
107
108
109
110
# File 'lib/paypal-sdk/core/api/rest.rb', line 105

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



149
150
151
152
153
154
# File 'lib/paypal-sdk/core/api/rest.rb', line 149

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

#tokenObject

Get access token



64
65
66
# File 'lib/paypal-sdk/core/api/rest.rb', line 64

def token
  token_hash[:access_token]
end

#token=(new_token) ⇒ Object

token setter



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

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_typeObject

Get access token type



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

def token_type
  token_hash[: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



79
80
81
82
83
84
85
# File 'lib/paypal-sdk/core/api/rest.rb', line 79

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