Automate Purchases With Paypal

To run purchases automatically without needing customer’s continuous authorization, You need to get baid (billing agreement id). Afterwards you can use Paypal reference transaction API to do future purchases.

Below is an example using active merchant gem to run Paypal API

active merchant example to get paypal baid by paypal express checkout api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Initialize Paypal API
def initialize
  @paypal ||= activemerchant::billing::paypalexpressgateway.new(
      :login => <paypal email account>,
      :password => <paypal password>,
      :signature => <paypal signature>,
end

# Ask for user agreement
def create
  setup_response = @paypal.setup_purchase(
  0,
  :return_url        => <your server path>,
  :cancel_return_url => <your server path>,
  :description => <product description>,
  :currency => "USD",
  :custom => "a customized data",
  :billing_agreement => {
      :type => 'MerchantInitiatedBilling', # Use this to retrieve BAID => Billing Agreement ID
      :payment_type => "Any" # seemed optional
  })
  redirect_to @paypal.redirect_url_for(setup_response.token)
end

# Get BAID
def callback
  response = @paypal.create_agreement(params[:token])
  if response.success?
      baid = response.params["BillingAgreementID"]
  end
end