Class: Paypal

Inherits:
Object
  • Object
show all
Includes:
CreditCardChecks
Defined in:
lib/ruby-paypal/paypal.rb

Overview

Author:: Chang Sau Sheong ([email protected]) Author:: Philippe F. Monnet ([email protected])

Copyright

Copyright © 2007-2009 Chang Sau Sheong & Philippe F. Monnet

License

Distributes under the same terms as Ruby

Version

0.0.5

:main: Paypal

Installing Ruby-PayPal

A lightweight ruby wrapper for PayPal NVP (Name-Value Pair) APIs. To install type the following at the command line:

$ gem install ruby-paypal

Using Ruby-PayPal

It’s critical that you understand how PayPal works and how the PayPal NVP API works. You should be relatively well-versed in the NVP API Developer Guide and Reference - see:

You should also visit and register yourself with the PayPal Developer Network and get a Sandbox account with in the PayPal Development Central (developer.paypal.com/).

Note that this library only supports the API signature method of securing the API credentials.

By setting Paypal.debug=true, the API will “pretty-print” the PayPal parameters to the console.

Direct Payment

To use credit card payment through PayPal, you need to use the DoDirectPayment APIs:

username = <PayPal API username> password = <PayPal API password> signature = <PayPal API signature> ipaddress = ‘192.168.1.1’ # can be any IP address amount = ‘100.00’ # amount paid card_type = ‘VISA’ # can be Visa, Mastercard, Amex etc card_no = ‘4512345678901234’ # credit card number exp_date = ‘022010’ # expiry date of the credit card first_name = ‘Sau Sheong’ last_name = ‘Chang’

paypal = Paypal.new(username, password, signature) # uses the PayPal sandbox
response = paypal.do_direct_payment_sale(ipaddress, amount, card_type,

card_no, exp_date, first_name, last_name) if response.ack == ‘Success’ then # do your thing end The above code is for a final sale only.

Note that the credit card number is checked against a modulo-10 algorithm (Luhn check) as well as a simple credit card type check. For more information please refer to en.wikipedia.org/wiki/Luhn_algorithm and en.wikipedia.org/wiki/Credit_card_number

Express Checkout

To use the customer’s PayPal account for payment, you will need to use the ExpressCheckout APIs:

<to be documented>

PayPal Subscriptions

PayPal Subscriptions is a service offering allowing you to sell subscriptions, consisting of an initial payment followed by several recurring payments. For a good technical overview, review the following guide:

Using the subscriptions service involve understanding the series of exchanges to perform using the NVP API. There are 3 key phases of a subscription:

  1. Creating a subscription request (and button for the customer)

  2. Customer review and confirmation on the PayPal site

  3. Processing of a subscription agreement

Each phase involves specific APIs.

Phase 1 - Subscription Request

In this phase, the do_set_express_checkout method will be called. PayPal will return a token we can use in subsequent API calls.

Let’s create a subcription request with the details of our subscription:

subscription_request = create_monthly_subscription_request( name=‘_Why’s Ruby Camping Adventures’, id=‘MNWRCA’, description=‘_Why’s Ruby Camping Adventures - Monthly Tips And Tricks For Camping Development’, invoice_number=‘INV20091122’, amount=‘5.00’)

Let’s call do_set_express_checkout to get a token back: response = paypal.do_set_express_checkout( return_url=‘www.yoursite.com/subscription-confirmed’, cancel_url=‘www.yoursite.com/subscription-aborted’, amount=‘5.00’, other_params=subscription_request) token = (response.ack == ‘Success’) ? response : ”

Let’s use the token to create a PayPal button to request payment via the sandbox:

form( { :method => ‘post’ , :action => ‘www.sandbox.paypal.com/cgi-bin/webscr’ #sandbox } ) do

input :id => ‘cmd’, :name => ‘cmd’, :type => ‘hidden’, :value => “_express-checkout”;

input :id => ‘token’, :name => ‘token’, :type => ‘hidden’, :value => “#token”;

input :id => ‘submit_subscription_request’, :name => ‘submit’, :type => ‘submit’, :value => ‘Subscribe Via PayPal’ end #form

Phase 2 - Customer Review and Confirmation

The customer will see the details of the subscription agreement we created previously. Upon confirmation, PayPal will redirect the customer to the return_url we specified passing the token back as well as the payerid.

Phase 3 = Subscription Processing

First we will retrieve the details of the check-out:

response = paypal.do_get_express_checkout_details(token)

Then we will execute the actual payment: response = paypal.do_express_checkout_payment(token=token, payment_action=‘Sale’, payer_id=payerid, amount=‘5.00’)

transaction_id = response

Now we can create the actual PayPal subscription

response = @paypal.do_create_recurring_payments_profile(token, start_date=‘2009-11-22 14:30:10’, profile_reference=‘INV20091122’, description=‘_Why’s Ruby Camping Adventures - Monthly Tips And Tricks For Camping Development’, billing_period=‘Month’, billing_frequency=1, total_billing_cycles=11, amount=‘5.00’, currency=‘USD’)

profile_id = @response

The profile_id can then be used in the future to access the details of the subscription, suspend it, reactivate it or cancel it using the following methods:

  • do_get_recurring_payments_profile_details

response = paypal.do_get_recurring_payments_profile_details(profile_id)

  • do_manage_recurring_payments_profile_status

# Suspend response = paypal.do_manage_recurring_payments_profile_status(profile_id, action=‘Suspend’, note=‘The subscription is being suspended due to payment cancellation by the customer’)

# Re-Activate response = paypal.do_manage_recurring_payments_profile_status(profile_id, action=‘Reactivate’, note=‘The subscription is being reactivated due to new payment by the customer’)

# Cancel response = paypal.do_manage_recurring_payments_profile_status(profile_id, action=‘Cancel’, note=‘The subscription is being cancelled due to cancellation of the account by the customer’) The customer information associated with the subscription can be retrieved using:

  • do_get_billing_agreement_customer_details

response = paypal.do_get_billing_agreement_customer_details(token)

Note: all subscriptions methods also accept an optional other_params hash for any other NVP you need to pass.

More information

Check for updates in our blogs:

Constant Summary collapse

@@debug =
false

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CreditCardChecks

#card_type_check, #luhn_check

Constructor Details

#initialize(user, password, signature, url = :sandbox, subject = nil) ⇒ Paypal

Create a new object with the given user name, password and signature. To enable production access to PayPal change the url to the live PayPal server. Set url to :production to change access to PayPal production servers.



267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/ruby-paypal/paypal.rb', line 267

def initialize(user, password, signature, url=:sandbox, subject=nil)
@api_parameters = {'USER' => user, 
  'PWD' => password, 
  'VERSION' => API_VERSION, 
  'SIGNATURE' => signature }
  if url == :sandbox
    @paypal_url = SANDBOX_SERVER
  elsif url == :production
    @paypal_url = PRODUCTION_SERVER
  else
    raise 'Invalid url specified'
  end
end

Class Method Details

.debugObject



253
254
255
# File 'lib/ruby-paypal/paypal.rb', line 253

def self.debug
	@@debug
end

.debug=(val) ⇒ Object

Controls whether or not PP debug statements will be produced and sent to the console



259
260
261
# File 'lib/ruby-paypal/paypal.rb', line 259

def self.debug=(val) #:doc:
	@@debug = val
end

Instance Method Details

#bin_check(bin) ⇒ Object

Checks and returns information on the card based on the given BIN (Bank Identification Number). Currently inactive since bindatabase.com is down.



450
451
452
# File 'lib/ruby-paypal/paypal.rb', line 450

def bin_check(bin)
  # stub for check to bindatabase.com, currently down
end

#do_authorization(transaction_id, amount, currency_code = 'USD') ⇒ Object

Does authorization of a request.

Equivalent of DoAuthorization.



384
385
386
387
388
389
390
391
392
393
# File 'lib/ruby-paypal/paypal.rb', line 384

def do_authorization(transaction_id, amount, currency_code = 'USD')
  params = {
    'METHOD' => 'DoAuthorization',
    'TRANSACTIONID' => transaction_id,
    'AMT' => amount.to_s,
    'TRANSACTIONENTITY' => 'Order',
    'CURRENCYCODE' => currency_code 
  }
  make_nvp_call(params)
end

#do_capture(authorization_id, amount, complete = true, currency_code = 'USD', invoice_no = nil, note = nil, soft_descriptor = nil) ⇒ Object

Captures payment for a transaction.

Equivalent of DoCapture.



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/ruby-paypal/paypal.rb', line 400

def do_capture(authorization_id, amount, complete=true, currency_code='USD', invoice_no=nil, note=nil, soft_descriptor=nil)
  params = {
    'METHOD' => 'DoCapture',
    'AUTHORIZATIONID' => authorization_id,
    'AMT' => amount.to_s,
    'CURRENCYCODE' => currency_code
  }
  if complete then
    params['COMPLETETYPE'] = 'Complete'
  else
    params['COMPLETETYPE'] = 'NotComplete'          
  end
  params['INVNUM'] = invoice_no unless invoice_no.nil?
  params['NOTE'] = note unless note.nil?
  params['SOFTDESCRIPTOR'] = soft_descriptor unless soft_descriptor.nil?                
  make_nvp_call(params)
end

#do_create_recurring_payments_profile(token, start_date, profile_reference, description, billing_period, billing_frequency, total_billing_cycles, amount, currency, other_params = {}) ⇒ Object

Creates a payment subscription based on a start date, billing period, frequency, number of periods and amount

Equivalent to CreateRecurringPaymentsProfile



491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/ruby-paypal/paypal.rb', line 491

def do_create_recurring_payments_profile(token, start_date, profile_reference, description, billing_period, billing_frequency, total_billing_cycles, amount, currency, other_params={})
 params = {
   'METHOD' => 'CreateRecurringPaymentsProfile',
   'TOKEN' => token,
		'PROFILESTARTDATE' => start_date,
		'PROFILEREFERENCE' => profile_reference,
		'DESC' => description,
		'BILLINGPERIOD' => billing_period,
		'BILLINGFREQUENCY' => billing_frequency,
		'TOTALBILLINGCYCLES' => total_billing_cycles,
		'AMT' => amount,
		'CURRENCYCODE' => currency
		} 
   params.merge! other_params

   make_nvp_call(params)
end

#do_direct_payment(payment_action, ipaddress, amount, credit_card_type, credit_card_no, expiry_date, first_name, last_name, cvv2 = nil, other_params = {}) ⇒ Object

Performs credit card payment with PayPal.

Equivalent of DoDirectPayment.

Performs Luhn check and a simple credit card type check based on the card number.



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/ruby-paypal/paypal.rb', line 309

def do_direct_payment(payment_action, ipaddress, amount, credit_card_type, 
credit_card_no, expiry_date, first_name, last_name, cvv2=nil, other_params={})
params = {
  'METHOD' => 'DoDirectPayment',
  'PAYMENTACTION' => payment_action,
  'AMT' => amount.to_s,
  'CREDITCARDTYPE' => credit_card_type,
  'ACCT' => credit_card_no,
  'EXPDATE' => expiry_date,
  'FIRSTNAME' => first_name,
  'LASTNAME' => last_name,
  'IPADDRESS' => ipaddress } 
  params['CVV2'] = cvv2 unless cvv2.nil?   
  params.merge! other_params

  raise 'Invalid credit card number' if not luhn_check(params['ACCT'])
  raise 'Invalid credit card type' if not card_type_check(params['CREDITCARDTYPE'], params['ACCT'])

  make_nvp_call(params)
end

#do_direct_payment_authorization(ipaddress, amount, credit_card_type, credit_card_no, expiry_date, first_name, last_name, cvv2 = nil, other_params = {}) ⇒ Object

Performs credit card payment with PayPal, but only requesting for authorization. You need to capture the funds later. Calls do_direct_payment.

Equivalent of DoDirectPayment with the PAYMENTACTION of ‘authorization’



286
287
288
289
290
# File 'lib/ruby-paypal/paypal.rb', line 286

def do_direct_payment_authorization(ipaddress, amount, credit_card_type, credit_card_no, expiry_date, 
  first_name, last_name, cvv2=nil, other_params={})
  do_direct_payment('Authorization', ipaddress, amount, credit_card_type, credit_card_no, 
  expiry_date, first_name, last_name, cvv2, other_params)
end

#do_direct_payment_sale(ipaddress, amount, credit_card_type, credit_card_no, expiry_date, first_name, last_name, cvv2 = nil, other_params = {}) ⇒ Object

Performs credit card payment with PayPal, finalizing the sale. Funds are captured immediately. Calls do_direct_payment.

Equivalent of DoDirectPayment with the PAYMENTACTION of ‘sale’



297
298
299
300
301
# File 'lib/ruby-paypal/paypal.rb', line 297

def do_direct_payment_sale(ipaddress, amount, credit_card_type, credit_card_no, expiry_date, 
  first_name, last_name, cvv2=nil, other_params={})
  do_direct_payment('Sale', ipaddress, amount, credit_card_type, credit_card_no, 
  expiry_date, first_name, last_name, cvv2, other_params)
end

#do_express_checkout_payment(token, payment_action, payer_id, amount, other_params = {}) ⇒ Object

Gets payment through PayPal for Express Checkout.

Equivalent of DoExpressCheckoutPayment



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

def do_express_checkout_payment(token, payment_action, payer_id, amount, other_params={})
  params = {
    'METHOD' => 'DoExpressCheckoutPayment',
    'TOKEN' => token,
    'PAYMENTACTION' => payment_action,
    'PAYERID' => payer_id,
    'AMT' => amount
  }   
  
  params.merge! other_params
  make_nvp_call(params)    
end

#do_get_billing_agreement_customer_details(token, other_params = {}) ⇒ Object

Retrieves the customer details for the billing agreement associated with the current token Equivalent to GetBillingAgreementCustomerDetails



544
545
546
547
548
549
550
551
552
# File 'lib/ruby-paypal/paypal.rb', line 544

def do_get_billing_agreement_customer_details(token, other_params={})
     params = {
       'METHOD' => 'GetBillingAgreementCustomerDetails',
       'TOKEN' => token
	} 
       params.merge! other_params

       make_nvp_call(params)
end

#do_get_express_checkout_details(token, other_params = {}) ⇒ Object

Retrieves the details of a express checkout for a given token

Equivalent to GetExpressCheckoutDetails



589
590
591
592
593
594
595
596
# File 'lib/ruby-paypal/paypal.rb', line 589

def do_get_express_checkout_details (token, other_params={})
params = {
  'METHOD' => 'GetExpressCheckoutDetails',
  'TOKEN' => token } 
  params.merge! other_params

  make_nvp_call(params)
end

#do_get_recurring_payments_profile_details(profile_id, other_params = {}) ⇒ Object

Equivalent to GetRecurringPaymentsProfileDetails



514
515
516
517
518
519
520
521
# File 'lib/ruby-paypal/paypal.rb', line 514

def do_get_recurring_payments_profile_details (profile_id, other_params={})
  params = {
    'METHOD' => 'GetRecurringPaymentsProfileDetails',
    'PROFILEID' => profile_id } 
    params.merge! other_params

    make_nvp_call(params)
end

#do_get_transaction_details(transaction_id, other_params = {}) ⇒ Object

Retrieves the details of a transaction for a given transaction id

Equivalent to GetTransactionDetails



576
577
578
579
580
581
582
583
# File 'lib/ruby-paypal/paypal.rb', line 576

def do_get_transaction_details (transaction_id, other_params={})
  params = {
    'METHOD' => 'GetTransactionDetails',
    'TRANSACTIONID' => transaction_id } 
    params.merge! other_params

    make_nvp_call(params)
end

#do_manage_recurring_payments_profile_status(profile_id, action, note = '', other_params = {}) ⇒ Object

Equivalent to ManageRecurringPaymentsProfileStatus



529
530
531
532
533
534
535
536
537
538
539
# File 'lib/ruby-paypal/paypal.rb', line 529

def do_manage_recurring_payments_profile_status(profile_id, action, note='', other_params={})
     params = {
       'METHOD' => 'ManageRecurringPaymentsProfileStatus',
       'PROFILEID' => profile_id,
	'ACTION' => action,
	'NOTE' => note
	} 
       params.merge! other_params

       make_nvp_call(params)
end

#do_mass_payment(payments, email_subject, receiver_type = 'EmailAddress', currency_code = 'USD') ⇒ Object

Perform mass payment to a group of recipients

Equivalent to MassPay



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/ruby-paypal/paypal.rb', line 459

def do_mass_payment(payments, email_subject, receiver_type='EmailAddress', currency_code='USD')
  if receiver_type != 'EmailAddress' then
    receiver_type = 'UserID'
  end
  
  params = {
    'METHOD' => 'MassPay',
    'RECEIVERTYPE' => receiver_type,
    'CURRENCYCODE' => currency_code,
    'EMAILSUBJECT' => email_subject
  }
  
  payments.each_index { |num|
    if receiver_type == 'EmailAddress' then
      params["L_EMAIL#{num}"] = payments[num].email
    else
      params["L_RECEIVERID#{num}"] = payments[num].receiver_id
    end
    params["L_UNIQUEID#{num}"] = payments[num].unique_id
    params["L_NOTE#{num}"] = payments[num].note
    params["L_AMT#{num}"] = payments[num].amount
  }
  
  make_nvp_call(params)        
end

#do_reauthorization(authorization_id, amount, currency_code = 'USD') ⇒ Object

Re-authorizes an authorized transaction.

Equivalent of DoReauthorization.



423
424
425
426
427
428
429
430
431
# File 'lib/ruby-paypal/paypal.rb', line 423

def do_reauthorization(authorization_id, amount, currency_code = 'USD')
  params = {
    'METHOD' => 'DoReauthorization',
    'AUTHORIZATIONID' => authorization_id,
    'AMT' => amount.to_s,
    'CURRENCYCODE' => currency_code 
  }
  make_nvp_call(params)
end

#do_set_billing_agreement_customer_details(return_url, cancel_url, billing_desc, billing_type = 'RecurringPayments', payment_type = '', custom = '', other_params = {}) ⇒ Object

Initiates the creation of a billing agreement Equivalent to SetCustomerBillingAgreement



557
558
559
560
561
562
563
564
565
566
567
568
569
570
# File 'lib/ruby-paypal/paypal.rb', line 557

def do_set_billing_agreement_customer_details(return_url, cancel_url, billing_desc, billing_type='RecurringPayments', payment_type='', custom='', other_params={})
     params = {
       'METHOD' => 'SetCustomerBillingAgreement',
		'RETURNURL' => return_url,
		'CANCELURL' => cancel_url,
		'L_BILLINGAGREEMENTDESCRIPTION0' => billing_desc,
		'L_BILLINGTYPE0' => billing_type,
		'L_PAYMENTTYPE0' => payment_type,
		'L_BILLINGAGREEMENTCUSTOM0' => custom
	} 
       params.merge! other_params

       make_nvp_call(params)
end

#do_set_express_checkout(return_url, cancel_url, amount, other_params = {}) ⇒ Object

Performs payment through PayPal.

Equivalent of SetExpressCheckout.



334
335
336
# File 'lib/ruby-paypal/paypal.rb', line 334

def do_set_express_checkout(return_url, cancel_url, amount, other_params={})
		return set_express_checkout(return_url, cancel_url, amount, other_params)
end

#do_transaction_search(start_date, payee_email, payer_email = '', payer_first = '', payer_middle = '', payer_last = '', transaction_class = 'Subscription', other_params = {}) ⇒ Object

Search transactions between payee and payer Equivalent to TransactionSearch



601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
# File 'lib/ruby-paypal/paypal.rb', line 601

def do_transaction_search(start_date,payee_email, payer_email='', payer_first='', payer_middle='', payer_last='', 
											transaction_class='Subscription', other_params={})
     params = {
       'METHOD' => 'TransactionSearch',
		'STARTDATE' => start_date,
		'RECEIVER' => payee_email,
		'TRANSACTIONCLASS' => transaction_class
	} 
	
	if !payer_email.nil? && !payer_email.empty?
		params['EMAIL'] = payer_email 
	else
		params['FIRSTNAME'] 		= payer_first		!payer_first.nil? && !payer_first.empty?
		params['MIDDLENAME']	= payer_middle	!payer_middle.nil? && !payer_middle.empty?
		params['LASTNAME'] 		= payer_last		!payer_last.nil? && !payer_last.empty?
	end
	
       params.merge! other_params

       make_nvp_call(params)
end

#get_express_checkout_details(token) ⇒ Object

Gets the details of the request started through set_express_checkout.

Equivalent of GetExpressCheckoutDetails.



353
354
355
356
357
358
359
# File 'lib/ruby-paypal/paypal.rb', line 353

def get_express_checkout_details(token)
  params = {
    'METHOD' => 'GetExpressCheckoutDetails',
    'TOKEN' => token 
  }
  make_nvp_call(params)    
end

#make_nvp_call(params) ⇒ Object

Makes the call to the PayPal NVP API. This is the workhorse method for the other method calls.



436
437
438
439
440
441
442
443
444
# File 'lib/ruby-paypal/paypal.rb', line 436

def make_nvp_call(params)
		pp params if @@debug
		
  @api_parameters.merge! params
  parameters = URI.escape(@api_parameters.to_a.collect {|pair| pair.join('=')}.join('&'))
  response = Net::HTTPS.post_form(URI.parse("https://#{@paypal_url}"), @api_parameters)
  response.error! unless response.kind_of? Net::HTTPSuccess
  PayPalResponse.new.merge get_hash(response.body)    
end

#set_express_checkout(return_url, cancel_url, amount, other_params = {}) ⇒ Object



338
339
340
341
342
343
344
345
346
347
# File 'lib/ruby-paypal/paypal.rb', line 338

def set_express_checkout(return_url, cancel_url, amount, other_params={})
  params = {
    'METHOD' => 'SetExpressCheckout',
    'RETURNURL' => return_url,
    'CANCELURL' => cancel_url,
    'AMT' => amount.to_s      
  }
  params.merge! other_params
  make_nvp_call(params)
end