This is the last part of a three-part series. As mentioned in the previous post, the next step is to define the PaypalExpress#purchase action so that we would get the paypal_express_purchase_path.
Modifying routes.rb
We first need to add this line to the routes.rb file so that Rails router would work properly:
Next, here’s the implementation of PaypalExpress#purchase action:
and the corresponding PaypalExpressHelper methods to go with it:
So, with this action defined, paypal_express_purchase_path should now be defined.
Now, let’s cover what this action does:
- When the customer gets redirected from the Paypal website back to our site, Paypal will send us two paramters:
tokenandpayer_id. The first thing we do, then, is to validate that these two values are supplied as part of the request parameters. If the parameters don’t exist, we redirect to the home page. - Next, we extract the parameters that ActiveMerchant’s
PaypalExpressGateway#purchaserequires. The two parameters that the purchase method requires are:- Total for the order (in cents)
- Purchase parameters (see:
PaypalExpressHelper#get_purchase_paramsmethod to see the parameters)
- The next step is the crux of the
purchaseaction. We callPaypalExpressGateway#purchaseand pass it the parameters from the previous step. - We then save the the return value of the
purchasemethod as purchase. The purchase object has asuccess?method which would tell you whether the operation was successful or not. If not, you can extract the error message via themessagemethod. - Finally, for my own app, I redirect to my home page. Of course, you are free to do whatever you want. I would suggest showing some form of notification or redirecting to a “post-purchase” page.
This concludes a simple tutorial on integrating Paypal Express with Rails using ActiveMerchant. I hope that it has been helpful! If you run into any problems with ActiveMerchant, I recommend ActiveMerchant Google Group.
Can you write an article on how to set it up without a cart? ive been having trouble with that.
I’ve fought with Paypal intgration before and eventually succeeded in getting it to work. This time i followed your series and had no problems (related to Paypal at least).
THANKS!