<< Grails and Error Handling | Home

Groovily Verifying a PayPal Event

I've been dealing with PayPal subscriptions for a little while now, using it to manage quite a complex subscription scheme. Though I encrypt my PayPal buttons, the notifications from PayPal are sent to an unencrypted URL, so I need check with PayPal to make sure the notifications are in fact from them. To do this, one sends back the notification's request parameters, to which PayPal respond with a 'VERIFIED' or 'INVALID' string.

After digging about for some Java code to do this, I couldn't resist converting it to Groovy. I like to do this, both to understand what the code does, and also to practice some of the Groovy APIs I don't get to use every day. And of course, any excuse to call one of my favourites, inject.
The code is quite terse:

def verifyIPN(request) {
    def names = request.getParameterNames().toList()
    def paramString = names.inject('cmd=_notify-validate') { result, name ->
        def value = request.getParameter(name)
        result << "&${name}=${URLEncoder.encode(value)}"
    }

    def url = new URL(grailsApplication.config.grails.paypal.url)
    def conn = url.openConnection()
    conn.setDoOutput(true)
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")

    conn.getOutputStream().withWriter { writer -> writer << paramString }
    return conn.getInputStream().withReader { reader -> reader.readLine() }
}
In the end, all I want is clear code.
I sometimes think my code will start appealing to Perl hackers. What do you think?




Add a comment Send a TrackBack