Module: Pingpp

Defined in:
lib/pingpp.rb,
lib/pingpp/util.rb,
lib/pingpp/event.rb,
lib/pingpp/charge.rb,
lib/pingpp/refund.rb,
lib/pingpp/version.rb,
lib/pingpp/webhook.rb,
lib/pingpp/transfer.rb,
lib/pingpp/list_object.rb,
lib/pingpp/api_resource.rb,
lib/pingpp/red_envelope.rb,
lib/pingpp/wx_pub_oauth.rb,
lib/pingpp/pingpp_object.rb,
lib/pingpp/identification.rb,
lib/pingpp/errors/api_error.rb,
lib/pingpp/api_operations/list.rb,
lib/pingpp/errors/pingpp_error.rb,
lib/pingpp/errors/channel_error.rb,
lib/pingpp/api_operations/create.rb,
lib/pingpp/api_operations/delete.rb,
lib/pingpp/api_operations/update.rb,
lib/pingpp/singleton_api_resource.rb,
lib/pingpp/errors/api_connection_error.rb,
lib/pingpp/errors/authentication_error.rb,
lib/pingpp/errors/invalid_request_error.rb

Defined Under Namespace

Modules: APIOperations, Util, Webhook, WxPubOauth Classes: APIConnectionError, APIError, APIResource, AuthenticationError, ChannelError, Charge, Event, Identification, InvalidRequestError, ListObject, PingppError, PingppObject, RedEnvelope, Refund, SingletonAPIResource, Transfer

Constant Summary collapse

DEFAULT_CA_BUNDLE_PATH =
File.dirname(__FILE__) + '/data/ca-certificates.crt'
HEADERS_TO_PARSE =
[:pingpp_one_version, :pingpp_sdk_version]
VERSION =
'2.0.14'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.api_baseObject

Returns the value of attribute api_base.



56
57
58
# File 'lib/pingpp.rb', line 56

def api_base
  @api_base
end

.api_keyObject

Returns the value of attribute api_key.



56
57
58
# File 'lib/pingpp.rb', line 56

def api_key
  @api_key
end

.api_versionObject

Returns the value of attribute api_version.



56
57
58
# File 'lib/pingpp.rb', line 56

def api_version
  @api_version
end

.parsed_headersObject

Returns the value of attribute parsed_headers.



56
57
58
# File 'lib/pingpp.rb', line 56

def parsed_headers
  @parsed_headers
end

.private_keyObject

Returns the value of attribute private_key.



56
57
58
# File 'lib/pingpp.rb', line 56

def private_key
  @private_key
end

.pub_keyObject

Returns the value of attribute pub_key.



56
57
58
# File 'lib/pingpp.rb', line 56

def pub_key
  @pub_key
end

.verify_ssl_certsObject

Returns the value of attribute verify_ssl_certs.



56
57
58
# File 'lib/pingpp.rb', line 56

def verify_ssl_certs
  @verify_ssl_certs
end

Class Method Details

.api_error(error, rcode, rbody, error_obj) ⇒ Object



273
274
275
# File 'lib/pingpp.rb', line 273

def self.api_error(error, rcode, rbody, error_obj)
  APIError.new(error[:message], rcode, rbody, error_obj)
end

.api_url(url = '') ⇒ Object



59
60
61
# File 'lib/pingpp.rb', line 59

def self.api_url(url='')
  @api_base + url
end

.authentication_error(error, rcode, rbody, error_obj) ⇒ Object



265
266
267
# File 'lib/pingpp.rb', line 265

def self.authentication_error(error, rcode, rbody, error_obj)
  AuthenticationError.new(error[:message], rcode, rbody, error_obj)
end

.channel_error(error, rcode, rbody, error_obj) ⇒ Object



269
270
271
# File 'lib/pingpp.rb', line 269

def self.channel_error(error, rcode, rbody, error_obj)
  ChannelError.new(error[:message], error[:code], error[:param], rcode, rbody, error_obj)
end

.execute_request(opts) ⇒ Object



203
204
205
# File 'lib/pingpp.rb', line 203

def self.execute_request(opts)
  RestClient::Request.execute(opts)
end

.general_api_error(rcode, rbody) ⇒ Object



232
233
234
235
# File 'lib/pingpp.rb', line 232

def self.general_api_error(rcode, rbody)
  APIError.new("Invalid response object from API: #{rbody.inspect} " +
               "(HTTP response code was #{rcode})", rcode, rbody)
end

.get_unameObject



167
168
169
170
171
# File 'lib/pingpp.rb', line 167

def self.get_uname
  `uname -a 2>/dev/null`.strip if RUBY_PLATFORM =~ /linux|darwin/i
rescue Errno::ENOMEM => ex # couldn't create subprocess
  "uname lookup failed"
end

.handle_api_error(rcode, rbody) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/pingpp.rb', line 237

def self.handle_api_error(rcode, rbody)
  begin
    error_obj = JSON.parse(rbody)
    error_obj = Util.symbolize_names(error_obj)
    error = error_obj[:error] or raise PingppError.new # escape from parsing

  rescue JSON::ParserError, PingppError
    raise general_api_error(rcode, rbody)
  end

  case rcode
  when 400, 404
    raise invalid_request_error error, rcode, rbody, error_obj
  when 401
    raise authentication_error error, rcode, rbody, error_obj
  when 402
    raise channel_error error, rcode, rbody, error_obj
  else
    raise api_error error, rcode, rbody, error_obj
  end

end

.handle_restclient_error(e) ⇒ Object

Raises:



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/pingpp.rb', line 277

def self.handle_restclient_error(e)
  connection_message = "Please check your internet connection and try again. " \
      "If this problem persists, you should check Pingpp's service status at " \
      "https://www.pingxx.com/status"

  case e
  when RestClient::RequestTimeout
    message = "Could not connect to Pingpp (#{@api_base}). #{connection_message}"

  when RestClient::ServerBrokeConnection
    message = "The connection to the server (#{@api_base}) broke before the " \
      "request completed. #{connection_message}"

  when RestClient::SSLCertificateNotVerified
    message = "Could not verify Pingpp's SSL certificate. " \
      "Please make sure that your network is not intercepting certificates. " \
      "(Try going to (#{@api_base}) in your browser.)"

  when SocketError
    message = "Unexpected error communicating when trying to connect to Pingpp. " \
      "You may be seeing this message because your DNS is not working. " \
      "To check, try running 'host pingxx.com' from the command line."

  else
    message = "Unexpected error communicating with Pingpp."

  end

  raise APIConnectionError.new(message + "\n\n(Network error: #{e.message})")
end

.invalid_request_error(error, rcode, rbody, error_obj) ⇒ Object



260
261
262
263
# File 'lib/pingpp.rb', line 260

def self.invalid_request_error(error, rcode, rbody, error_obj)
  InvalidRequestError.new(error[:message], error[:param], rcode,
                          rbody, error_obj)
end

.parse(response) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
# File 'lib/pingpp.rb', line 207

def self.parse(response)
  begin
    # Would use :symbolize_names => true, but apparently there is
    # some library out there that makes symbolize_names not work.
    response = JSON.parse(response.body)
  rescue JSON::ParserError
    raise general_api_error(response.code, response.body)
  end

  Util.symbolize_names(response)
end

.parse_headers(headers) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/pingpp.rb', line 63

def self.parse_headers(headers)
  @parsed_headers = {}
  if headers && headers.respond_to?("each")
    headers.each do |k, v|
      k = k[0, 5] == 'HTTP_' ? k[5..-1] : k
      header_key = k.gsub(/-/, '_').to_s.downcase.to_sym
      if HEADERS_TO_PARSE.include?(header_key)
        if v.is_a?(String)
          @parsed_headers[header_key] = v
        elsif v.is_a?(Array)
          @parsed_headers[header_key] = v[0]
        end
      end
    end
  end
end

.private_key_path=(private_key_path) ⇒ Object



219
220
221
# File 'lib/pingpp.rb', line 219

def self.private_key_path=(private_key_path)
  @private_key = File.read(private_key_path)
end

.pub_key_path=(pub_key_path) ⇒ Object



223
224
225
# File 'lib/pingpp.rb', line 223

def self.pub_key_path=(pub_key_path)
  @pub_key = File.read(pub_key_path)
end

.request(method, url, api_key, params = {}, headers = {}) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/pingpp.rb', line 80

def self.request(method, url, api_key, params={}, headers={})
  unless api_key ||= @api_key
    raise AuthenticationError.new('No API key provided. ' +
      'Set your API key using "Pingpp.api_key = <API-KEY>". ' +
      'You can generate API keys from the Pingpp web interface. ' +
      'See https://pingxx.com/document/api for details.')
  end

  if api_key =~ /\s/
    raise AuthenticationError.new('Your API key is invalid, as it contains ' +
      'whitespace. (HINT: You can double-check your API key from the ' +
      'Pingpp web interface. See https://pingxx.com/document/api for details.)')
  end

  if verify_ssl_certs
    request_opts = {:verify_ssl => OpenSSL::SSL::VERIFY_PEER,
                    :ssl_ca_file => @ssl_bundle_path,
                    :ssl_version => 'TLSv1'}
  else
    request_opts = {:verify_ssl => false,
                    :ssl_version => 'TLSv1'}
    unless @verify_ssl_warned
      @verify_ssl_warned = true
      $stderr.puts("WARNING: Running without SSL cert verification. " \
        "You should never do this in production. " \
        "Execute 'Pingpp.verify_ssl_certs = true' to enable verification.")
    end
  end

  params = Util.objects_to_ids(params)
  url = api_url(url)

  case method.to_s.downcase.to_sym
  when :get, :head, :delete
    # Make params into GET parameters
    url += "#{URI.parse(url).query ? '&' : '?'}#{uri_encode(params)}" if params && params.any?
    payload = nil
  else
    payload = JSON.generate(params)
  end

  request_opts.update(:headers => request_headers(api_key, method.to_s.downcase.to_sym == :post, payload).update(headers),
                      :method => method, :open_timeout => 30,
                      :payload => payload, :url => url, :timeout => 80)

  begin
    response = execute_request(request_opts)
  rescue SocketError => e
    handle_restclient_error(e)
  rescue NoMethodError => e
    # Work around RestClient bug
    if e.message =~ /\WRequestFailed\W/
      e = APIConnectionError.new('Unexpected HTTP response code')
      handle_restclient_error(e)
    else
      raise
    end
  rescue RestClient::ExceptionWithResponse => e
    if rcode = e.http_code and rbody = e.http_body
      handle_api_error(rcode, rbody)
    else
      handle_restclient_error(e)
    end
  rescue RestClient::Exception, Errno::ECONNREFUSED => e
    handle_restclient_error(e)
  end

  [parse(response), api_key]
end

.request_headers(api_key, is_post = false, data = nil) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/pingpp.rb', line 178

def self.request_headers(api_key, is_post=false, data=nil)
  headers = {
    :user_agent => "Pingpp/v1 RubyBindings/#{Pingpp::VERSION}",
    :authorization => "Bearer #{api_key}",
    :content_type => is_post ? 'application/json' : 'application/x-www-form-urlencoded'
  }

  headers[:pingplusplus_version] = api_version if api_version
  headers.update(parsed_headers) if parsed_headers && !parsed_headers.empty?

  begin
    headers.update(:x_pingpp_client_user_agent => JSON.generate(user_agent))
  rescue => e
    headers.update(:x_pingpp_client_raw_user_agent => user_agent.inspect,
                   :error => "#{e} (#{e.class})")
  end

  if is_post && private_key && data
    signature = sign_request(data, private_key)
    headers.update(:pingplusplus_signature => signature)
  end

  headers
end

.sign_request(data, pri_key) ⇒ Object



227
228
229
230
# File 'lib/pingpp.rb', line 227

def self.sign_request(data, pri_key)
  pkey = OpenSSL::PKey.read(pri_key)
  return Base64.strict_encode64(pkey.sign(OpenSSL::Digest::SHA256.new, data))
end

.uri_encode(params) ⇒ Object



173
174
175
176
# File 'lib/pingpp.rb', line 173

def self.uri_encode(params)
  Util.flatten_params(params).
    map { |k,v| "#{k}=#{Util.url_encode(v)}" }.join('&')
end

.user_agentObject



152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/pingpp.rb', line 152

def self.user_agent
  @uname ||= get_uname
  lang_version = "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})"

  {
    :bindings_version => Pingpp::VERSION,
    :lang => 'ruby',
    :lang_version => lang_version,
    :platform => RUBY_PLATFORM,
    :publisher => 'pingpp',
    :uname => @uname
  }

end