Ruby on Rails
Active Merchant PayPal Tips

There is not a lot of documentation for Active Merchant, so here are a few tips to help you out when using it for PayPal Payments Pro:


config.after_initialize do
	ActiveMerchant::Billing::PaypalGateway.pem_file =
		File.read(File.dirname(__FILE__) + '/../paypal/paypal.pem')
end

  1. This would go in paypal_success
    response = gateway.get_express_details(params“token”)
    if response.success?
    @cart = Cart.find(response.params‘invoice_id’)
    # Now show some kind of confirmation screen
    # After user clicks ‘Confirm payment’ execute something like
    # this to secure the funds:
    response = paypal_gateway.purchase(
    @order.total_price_in_cents,
    nil,
    :express => true,
    :token => params“token”,
    :payer_id => params“PayerID”
    )

    if response.success?
    # Sing and dance, etc.
    end
    end

Using the sandbox mode

To use Active Merchant in the sandbox mode, you have to add this line

      ActiveMerchant::Billing::Base.gateway_mode = :test
either in your environment.rb or your production.rb / development.rb or your controller file.

Issues with having both direct payment and paypal express:

If you initialized the paypal PEM file in environment.rb [or other environment file], then either direct payment or express payment fails with a “Security header is invalid” error. The root cause is initializing the PEM file in the environment files does not work correctly. Instead initialize the PEM file when you create the gateway like this:


@@pem_file = File.read(File.join(RAILS_ROOT, 'config', 'paypal', 'paypal.pem')) @@gateway = ActiveMerchant::Billing::Base.gateway(:paypal).new( :login => login, :password => pass, :pem => @@pem_file


—-

If you need to implement just the paypal express checkout function you may also use the PayPal Plugin (release by JadedPixel) that is better documented than ActiveMerchant. I wrote a simple tutorial on how using Payapal Express Checkout with Ruby on Rails that could be useful.