Class: PayPalBusiness::API

Inherits:
Object
  • Object
show all
Defined in:
lib/paypal-business/paypal.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(credentials, live = false) ⇒ API

Returns a new instance of API.



54
55
56
57
58
59
60
61
62
# File 'lib/paypal-business/paypal.rb', line 54

def initialize(credentials, live=false)
  credentials = YAML::load(ERB.new(File.read(credentials)).result).to_options if credentials.is_a?(String)
  
	@cert_file = credentials[:cert_file]
	@key_file = credentials[:key_file]
	@username = credentials[:username]
	@password = credentials[:password]
	@live = live
end

Instance Attribute Details

#cert_fileObject

Returns the value of attribute cert_file.



49
50
51
# File 'lib/paypal-business/paypal.rb', line 49

def cert_file
  @cert_file
end

#key_fileObject

Returns the value of attribute key_file.



50
51
52
# File 'lib/paypal-business/paypal.rb', line 50

def key_file
  @key_file
end

#passwordObject

Returns the value of attribute password.



52
53
54
# File 'lib/paypal-business/paypal.rb', line 52

def password
  @password
end

#usernameObject

Returns the value of attribute username.



51
52
53
# File 'lib/paypal-business/paypal.rb', line 51

def username
  @username
end

Instance Method Details

#authorize(params) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/paypal-business/paypal.rb', line 352

def authorize(params)
  client = create_aa_client
  authreqtype = DoAuthorizationRequestType.new
  authreqtype.version = "2.0"
  authreq = DoAuthorizationReq.new
  authreq.doAuthorizationRequest = authreqtype
  authreqtype.transactionID = params[:transactionID]
  bamount = BasicAmountType.new(params[:amount])
  bamount.xmlattr_currencyID='USD'
  authreqtype.amount = bamount
  res = client.doAuthorization(authreq)
  return res
end

#capture(params) ⇒ Object

Function: capture

This funcion performs a doCapture.  It captures or collects the charge from a previously authorized
transaction.  This transaction is referenced by the transactionID returned from directauth.

The return value of this function is either "Success" or "Failure"

The parameter hash for this function is to be in the following form:
            :transactionID => "<RETURN FROM PREVIOUS DIRECT AUTH>"
            :amount = > "<AMOUNT TO CHARGE>" //should be less than or equal to
                                             //auth's amount
**WARNING*** This function is currently not functioning correctly.  It throws NoMethodErrors even when successfuly making a capture.
    Even when running in debug mode with wiredumps the responses from paypal are have Ack values of Success.  Indicating an error in the parsing of the response outside this plugin.


320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/paypal-business/paypal.rb', line 320

def capture(params)
  client = create_aa_client
  capturetype = DoCaptureRequestType.new
  capturetype.version = "2.0"
  capturereq = DoCaptureReq.new
  capturereq.doCaptureRequest = capturetype
  capturetype.authorizationID = params[:transactionID]

  #bamount = AmountType.new(params[:amount])
  #bamount.xmlattr_currencyID="USD"
  # bamount = "<Amount currencyID=\"USD\">#{params[:amount]}</Amount>"

  # JS HACK:
  ns = "urn:ebay:apis:eBLBaseComponents" 
  otqname = XSD::QName.new(nil, "Amount")
  otele = SOAP::SOAPElement.new(otqname, "#{params[:amount]}")
  otele.extraattr["currencyID"] = "USD" 
  bamount = otele

  capturetype.amount = bamount
  capturetype.completeType = "Complete"
  #begin
    res = client.doCapture(capturereq)
    #puts res.paymentStatus
    #return res.ack
    return res
  #rescue NoMethodError
    # puts "Error Caught, Status lost\n"
    # return "Failure"
  #end
end

#create_aa_clientObject

Create the paypal client to communicate with the paypal web services api. Internaly used function



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/paypal-business/paypal.rb', line 72

def create_aa_client
  if(self.live?)
    endpoint_url='https://api.paypal.com/2.0/'
  end
  client = PayPalAPIAAInterface.new(endpoint_url)
  client.options['protocol.http.ssl_config.verify_mode'] = OpenSSL::SSL::VERIFY_NONE  # used to be VERIFY_PEER
  client.options['protocol.http.ssl_config.ca_file'] = File.dirname(__FILE__) + '/api_cert_chain.crt'
  
  client.options['protocol.http.ssl_config.client_cert'] = @cert_file
  client.options['protocol.http.ssl_config.client_key'] = @key_file
  client.headerhandler << RequesterCredentialsHandler.new(@username, @password, '')
  
  # run ruby with -d to see SOAP wiredumps.
  client.wiredump_dev = STDERR if $DEBUG
  client
end

#create_clientObject



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/paypal-business/paypal.rb', line 89

def create_client
   if(self.live?)
    endpoint_url='https://api.paypal.com/2.0/'
  end
  client = PayPalAPIInterface.new(endpoint_url)
  client.options['protocol.http.ssl_config.verify_mode'] = OpenSSL::SSL::VERIFY_NONE  # used to be VERIFY_PEER
  client.options['protocol.http.ssl_config.ca_file'] = File.dirname(__FILE__) + '/api_cert_chain.crt'
  
  client.options['protocol.http.ssl_config.client_cert'] = @cert_file
  client.options['protocol.http.ssl_config.client_key'] = @key_file
  client.headerhandler << RequesterCredentialsHandler.new(@username, @password, '')
  
  # run ruby with -d to see SOAP wiredumps.
  client.wiredump_dev = STDERR if $DEBUG
  client
end

#directauth(params) ⇒ Object

Function: directauth

This function performs a directcharge in authorization mode.  This means no actual funds are
transfered upon comletetion of this action.

The return value of this function is either "Failure" or the transactionID for the authorization.
The transactionID is needed if you intend to capture the funds authroized by this function.
The method expects the param hash to be in the form of :
             :firstName => "<FIRST_NAME_VALUE>",
             :lastName => "<LAST_NAME_VALUE>",
             :ip => "<BUYERS_IP_ADDRESS",
             :amount => "<AMOUNT_TO_CHARGE>",    //This value has a maximum of 10,000.00
             :itemName => "<ITEM_THAT_IS_BEING_SOLD",
             :addressName => "Billing",
             :street1 => "<FIRST LINE OF STREET ADDRESS>",
             :street2 => "<SECOND LINE OF STREET ADDRESS>",
             :cityName => "<CITY OF BILLING ADDRESS OF CARD>",
             :postalCode =>  "<ZIPCODE OF BILLING ADDRESS OF CARD>",
             :stateOrProvince => "<STATECODE OF BILLING ADDRESS>",
             :country => "<COUNTRY CODE OF BILLING ADDRESS>",
             :creditCardType => "Visa or MasterCard or Amex or Discover",
             :creditCardNumber => "<VALID CREDIT CARD NUMBER",
             :cVV2 => "<CVV2 AUTHORIZATION NUMBER FROM CARD"
             :expMonth => 1  ,  //Expiration month in numerical form not string
             :expYear => 2006     ///Expiration year in numerical form


233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
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
# File 'lib/paypal-business/paypal.rb', line 233

def directauth(params)
    client = create_aa_client

    directreq = DoDirectPaymentReq.new
    drtype = DoDirectPaymentRequestType.new
    directreq.doDirectPaymentRequest = drtype
    drtype.version = "2.0"
    dtype = DoDirectPaymentRequestDetailsType.new
    dtype.iPAddress = params[:ip]

    # JS HACK:
    ns = "urn:ebay:apis:eBLBaseComponents" 
    otqname = XSD::QName.new(ns, "OrderTotal")
    otele = SOAP::SOAPElement.new(otqname, "#{params[:amount]}")
    otele.extraattr["currencyID"] = "USD" 
    bamount = otele


    #logger.debug( "Amount in Paypal: #{params[:amount]}")
    pdetails = PaymentDetailsType.new
    #bamount = BasicAmountType.new("#{params[:amount]}")
    #bamount.xmlattr_currencyID='USD'#currentlyonlysupports USD

    pdetails.orderTotal = bamount
    dtype.paymentDetails = pdetails

    drtype.doDirectPaymentRequestDetails = dtype
    dcard = CreditCardDetailsType.new
    dtype.paymentAction = "Authorization"
    payerinfo = PayerInfoType.new
    addr = AddressType.new
    addr.name = params[:addressName]
    addr.street1 = params[:street1]
    addr.street2 = params[:street2]
    addr.cityName = params[:cityName]
    addr.postalCode = params[:postalCode]
    addr.stateOrProvince = params[:stateOrProvince]
    addr.country = params[:country]
    dcard.creditCardType = case params[:creditCardType].downcase
      when 'mastercard'
       'MasterCard'
      when 'discover'
       'Discover'
      when 'amex', 'americanexpress', 'american express'
       'Amex'
      else
       'Visa'
    end
    dcard.creditCardNumber =  params[:creditCardNumber]
    if (params[:cVV2]==nil)
	dcard.cVV2 = "000"
    else
	dcard.cVV2 =  params[:cVV2]
    end
    dcard.expMonth = params[:expMonth]
    dcard.expYear  = params[:expYear]
    pname = PersonNameType.new
    pname.firstName = params[:firstName]
    pname.lastName = params[:lastName]
    payerinfo.payerName = pname
    paydetailssitem = PaymentDetailsItemType.new
    paydetailssitem.name = params[:itemName]
    dtype.creditCard = dcard
    dcard.cardOwner = payerinfo
    payerinfo.address = addr
    pdetails.shipToAddress = addr
    res = client.doDirectPayment(directreq)
    puts res.ack if $DEBUG
    #res.ack
    return res
end

#directcharge(params) ⇒ Object

Function: directcharge

This function performs a doDirectCharge action.  Transfering funds from the parameter's account to your paypal merchant account.

The return value of this function is either "Success" or "Failure"  depending on validity of input.

The directcharge method takes a hash argument (params).
The method expects the hash to be in the form of:
             :firstName => "xxxx",
             :lastName => "xxxxxx",
             :ip => "127.0.0.1",
             :amount => "10,000",
             :itemName => "Item",
             :addressName => "Home",
             :street1 => "<STREET 1 of BILLING ADDRESS",
             :street2 => "<STREET 2 OF Billing address (optional)",
             :cityName => "<City name of billing address>",
             :postalCode =>  "<Postal code for billing address>",
             :stateOrProvince => "<State of billing address>",
             :country => "<Country Code for billing address (ex US)",
             :creditCardType => "<Credit Card type (Visa, MasterCard, Amex, Discover)>",
             :creditCardNumber => "<Buyers credit card number>",
             :cVV2 => "<Authorization number (last 3 digits on back of ccard>"
             :expMonth => 7,//example
             :expYear => 2999 //example


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/paypal-business/paypal.rb', line 132

def directcharge(params)
  client = create_aa_client

  directreq = DoDirectPaymentReq.new
  drtype = DoDirectPaymentRequestType.new
  directreq.doDirectPaymentRequest = drtype
  drtype.version = "2.0"
  dtype = DoDirectPaymentRequestDetailsType.new
  dtype.iPAddress = params[:ip]

  # JS HACK:
  # currencyID attribute does NOT get set correctly by the webservices stub
  # solution: insert attribute into the soap message
  ns = "urn:ebay:apis:eBLBaseComponents" 
  otqname = XSD::QName.new(ns, "OrderTotal")
  otele = SOAP::SOAPElement.new(otqname, "#{params[:amount]}")
  otele.extraattr["currencyID"] = "USD"
  bamount = otele


  #logger.debug( "Amount in Paypal: #{params[:amount]}")
  pdetails = PaymentDetailsType.new
  #bamount = BasicAmountType.new("#{params[:amount]}")
  #bamount.xmlattr_currencyID='USD'#currentlyonlysupports USD

  pdetails.orderTotal = bamount
  dtype.paymentDetails = pdetails

  drtype.doDirectPaymentRequestDetails = dtype
  dcard = CreditCardDetailsType.new
  dtype.paymentAction = "Sale"
  payerinfo = PayerInfoType.new
  addr = AddressType.new
  addr.name = params[:addressName]
  addr.street1 = params[:street1]
  addr.street2 = params[:street2]
  addr.cityName = params[:cityName]
  addr.postalCode = params[:postalCode]
  addr.stateOrProvince = params[:stateOrProvince]
  addr.country = params[:country]
  dcard.creditCardType = case params[:creditCardType].downcase
    when 'mastercard'
     'MasterCard'
    when 'discover'
     'Discover'
    when 'amex', 'americanexpress', 'american express'
     'Amex'
    else
     'Visa'
  end
  dcard.creditCardNumber =  params[:creditCardNumber]
  if (params[:cVV2]==nil)
  	dcard.cVV2 = "000"
  else
  	dcard.cVV2 =  params[:cVV2]
  end
  dcard.expMonth = params[:expMonth]
  dcard.expYear  = params[:expYear]
  pname = PersonNameType.new
  pname.firstName = params[:firstName]
  pname.lastName = params[:lastName]
  payerinfo.payerName = pname
  paydetailssitem = PaymentDetailsItemType.new
  paydetailssitem.name = params[:itemName]
  dtype.creditCard = dcard
  dcard.cardOwner = payerinfo
  payerinfo.address = addr
  pdetails.shipToAddress = addr
  res = client.doDirectPayment(directreq)
  puts res.ack if $DEBUG
  #res.ack
  return res
end

#live?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/paypal-business/paypal.rb', line 64

def live?
  @live
end

#mass_pay(params) ⇒ Object



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/paypal-business/paypal.rb', line 391

def mass_pay(params)
  raise "Expected parameter 'items' to Paypal.mass_pay as an array of hashes with keys :email, :amount, :note (optional)" if params[:items].nil?
  raise "Expected more than 0 and less than 251 items to Paypal.mass_pay" if params[:items].size < 1 || params[:items].size > 250
  client = create_client
  massreqtype = MassPayRequestType.new
  massreqtype.version = "2.0"
  massreqtype.emailSubject = params[:email_subject] if params[:email_subject]
  massreqtype.receiverType = "EmailAddress"
  massreq = MassPayReq.new
  massreq.massPayRequest = massreqtype
  massitems = []
  for i in params[:items]
    raise "Failed to process item #{i.inspect}, because it did not contain an email and/or amount" if i[:amount].nil? || i[:email].nil?
    it = MassPayRequestItemType.new
    it.receiverEmail = i[:email]
    #amt = BasicAmountType.new(i[:amount])

    # JS HACK:
    # currencyID attribute does NOT get set correctly by the webservices stub
    # solution: insert attribute into the soap message
    ns = "urn:ebay:api:PayPalAPI" 
    otqname = XSD::QName.new(ns, "Amount")
    otele = SOAP::SOAPElement.new(otqname, "#{i[:amount]}")
    otele.extraattr["currencyID"] = "USD"

    it.amount = otele
    it.note = i[:note] if i[:note]
    massitems << it
  end
  massreqtype.massPayItem = massitems
  res = client.massPay(massreq)    
  return res
end

#reauthorize(params) ⇒ Object



366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/paypal-business/paypal.rb', line 366

def reauthorize(params)
  client = create_aa_client
  reauthreqtype = DoReauthorizationRequestType.new
  reauthreqtype.version = "2.0"
  reauthreq = DoReauthorizationReq.new
  reauthreq.doReauthorizationRequest = reauthreqtype
  reauthreqtype.authorizationID = params[:transactionID]
  bamount = BasicAmountType.new(params[:amount])
  bamount.xmlattr_currencyID='USD'
  reauthreqtype.amount = bamount
  res = client.doReauthorization(reauthreq)
  return res
end

#void(params) ⇒ Object



380
381
382
383
384
385
386
387
388
389
# File 'lib/paypal-business/paypal.rb', line 380

def void(params)
  client = create_aa_client
  voidreqtype = DoVoidRequestType.new
  voidreqtype.version = "2.0"
  voidreq = DoVoidReq.new
  voidreq.doVoidRequest = voidreqtype
  voidreqtype.authorizationID = params[:transactionID]
  res = client.doVoid(voidreq)
  return res
end