Automated Billing and Faxing for the Web - Getting a Transaction Notification continued
(Page 4 of 5 )
Example 6-3. A PayPal receipt
package com.cascadetg.ch06;
import java.util.*;
import java.net.*;
import java.io.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
public class PayPalReciept
{
// Used to store retrived values from the PayPal submission.
String paymentStatus;
String txnId;
String receiverEmail;
String payerEmail;
private static final boolean debug = false;
// System.getProperty line to get the proper new line character[s].
String newLine = System.getProperty("line.separator", ".");
// Keep track of sent transactions. Note that this is in-memory
// storage only - for a "real" system you would want to persist
// this information, as well as the rest of fields of this object.
// (mostly likely to a database of some sort).
private static Hashtable processedTxnId = new Hashtable();
// This method takes an incoming request and validates it both
// against the PayPal server and some internal logic.
public boolean validateRequest(HttpServletRequest request)
{
try
{
// Read the post from PayPal system.
Enumeration parameters = request.getParameterNames();
// We then add a "cmd" attribute to send back to PayPal
// to indicate that we want to validate the request.
StringBuffer send =
new StringBuffer("cmd=_notify-validate");
// Here, we put all of the parameters passed in from the
// PayPal notification POST.
while (parameters.hasMoreElements())
{
String paramName = (String)parameters.nextElement();
String paramValue = request.getParameter(paramName);
send.append("&");
send.append(paramName);
send.append("=");
send.append(URLEncoder.encode(paramValue));
}
if (debug)
System.out.println(send.toString());
// This next sequence opens a connection to the PayPal
// server, sets up the connection, and writes the sent
// parameters back to the PayPal server.
URL paypalServer =
new URL(https://www.paypal.com/cgi-bin/webscr);
URLConnection paypalConnection =
paypalServer.openConnection();
paypalConnection.setDoOutput(true);
paypalConnection.setRequestProperty(
"Content-Type",
"application/x-www-form-urlencoded");
PrintWriter paypalServerWriter =
new PrintWriter(paypalConnection.getOutputStream());
paypalServerWriter.println(send);
paypalServerWriter.close();
if (debug)
System.out.println("Sent to PayPal server.");
// We then need to read the response from the PayPal
// server.
BufferedReader in =
new BufferedReader(
new InputStreamReader(
paypalConnection.getInputStream()));
String paypalResponse = in.readLine();
in.close();
if (debug)
System.out.println(
"Read PayPal server response = " + paypalResponse);
// Set the values of this object from the values sent
// by the initial request. If these values are verified,
// we'll want them for later. If the values aren't
// verified, or something else is wrong, we'll want
// to track them for logging purposes.
setValues(request);
// If everything is ok, the response back should be
// VERIFIED. Otherwise, something went wrong.
if (paypalResponse.equals("VERIFIED"))
{
// If it isn't completed, it's a status message of
// some sort. We're only interested in Completed
// payments.
if (!paymentStatus.equals("Completed"))
return false;
// Make sure that we are the actual recipients of
// the money.
if (receiverEmail
.compareToIgnoreCase(PayPalTokens.paypalEmail)
!= 0)
return false;
// Check the in-memory cache to verify that we
// haven't already handled this transaction.
if (processedTxnId.get(this.getTxnId()) != null)
return false;
// Everything looks good, so let's add this to the
// transaction cache.
processedTxnId.put(this.getTxnId(), this.getTxnId());
return true;
} else
{
System.out.println("Invalid PayPal transaction!");
System.out.println(this.toString());
return false;
}
} catch (Exception e)
{
System.out.println("Unable to connect to PayPal server.");
e.printStackTrace();
return false;
}
}
// "Flatten" the object to a String.
public String toString()
{
StringBuffer output = new StringBuffer();
Enumeration outEnum = this.getAttributes().keys();
while (outEnum.hasMoreElements())
{
String outputStr = (String)outEnum.nextElement();
output.append(outputStr);
output.append(" : ");
output.append(paypalAttributes.get(outputStr).toString());
output.append(newLine);
}
return output.toString();
}
public String toHTMLString()
{
StringBuffer htmlString = new StringBuffer();
htmlString.append("<HTML><BODY>");
htmlString.append("<TABLE HEIGHT='100%' WIDTH='100%'>");
htmlString.append("<TR><TD>");
Enumeration myValues = this.getAttributes().keys();
while (myValues.hasMoreElements())
{
String next = (String)myValues.nextElement();
htmlString.append(next);
htmlString.append(" : ");
htmlString.append(this.getAttribute(next).toString());
htmlString.append("<BR>");
htmlString.append(newLine);
}
htmlString.append("</TD></TR></TABLE>