Tuesday, June 21, 2011

Spring Webflow PayPal Integration

Recently I've been helping with a project that used Spring Webflow and required integration with PayPal and other payment systems. When customer selects PayPal as a payment method application will forward request to the PayPal website and loses control of the flow. Customer on the PayPal website can finish payment or cancel and should be forwarded back to a certain view state depending on the made choice.

So the question is :
Is there is way to enter a particular state within the flow once the request comes back from PayPal?

The basic idea of the solution to this problem was:

  1. Get current session so it will be used to restore flow from the session
  2. Define event for each case (cancelled and approved) and generate urls
  3. Redirect to PayPal website.

Once customer will be redirected from PayPal website Webflow will retrieve current state and make a transition based on the event to another state.

Here is a simple example:

public void SomeServiceMethod(Object someObjects, RequestContext context) {
   
   //get http request  
   HttpServletRequest request = (HttpServletRequest)
                    context.getExternalContext().getNativeRequest();
   //generate Spring Webflow return URL
   String url = request.getRequestURL() + 
                    ";jsessionid="+ request.getSession().getId() + "?" +
                    request.getQueryString();

   String paypalCancelUrl   = url + "&_eventId=cancel";
   String paypalApprovedUrl = url + "&_eventId=approved";

   //redirect to PayPal using the above URLs.
}