Paypal adaptive API and Spring 3 rest template — Part 3
This is part 3 and the final part of this series of how to use Spring 3 rest template and paypal’s adaptive API. You can find part 1 and part 2 here and here. This part is all about unmarshalling paypal’s responds back to your expected objects. The problem need to be solve here is that paypal replies with 200 even if the pay request have failed for what ever reason (that is not HTTP related). Compounded by the fact that the the success response have a different parent tag to a failed response even tho the object structure is the same (JAXB doesn’t support multiple XMLRootElements).
There could be another way to skin this cat if you have post a alternative solution here will give readers a alternative option
Solution Objective:
I wanted to keep my code as clean and transparent as possible in relation the code that is making the REST call, which should do not more then this line:
ResponseEntity
responseEntity = restOperations.postForEntity(paypalProperties.getAdaptiveUrl(), entity, PaypalPayReply.class);
Also to keep non business related unit tests at a minium I need to eliminate any if else statements by pushing all type mapping decisions to spring.
Solution Resources:
In this part you will be using Spring OXM and writing your own HttpMessageConverter to unmarshall the correct object back to the caller. All code is available at github.
Paypal XML Success/Fail similarities:
Both success and failure messages has a ‘responseEnvelope’ element that contains a ‘ack’ element which indicates Success or failure of the request. Take a look at this (success) and this (failure) Jaxb2 Objects. I use the ‘ack’ element to determine different business rules.
Setting up a custom HttpMessageConverter:
The line of code you see in ‘solution objective’ returns PaypalPayReply interface, inorder for spring to know how to unmashall this we have to use a custom HttpMessageConverter. Implementing your own give you a chance to hook into the spring rest unmarshalling/marshalling process. The class that does this is at rest.reply.PaypalReplyHttpConvertor. Once you have set it up make sure you have added it to your spring config.
Finally setting up OXM:
In order for the the HttpMessageConverter to work properly you need to set up your OXM mapper, and its relative config and code here.
Thats it the final piece of information is about paypal’s IPN which you are likley to be using. When testing this make sure you always receive the related IPN message, otherwise paypal will degrade the frequency of messages and makes testing very difficult.
