To integrate PayPal in your applications first go to https://developer.paypal.com/ and create a developer account in PayPal. Then sign in to the account using created credentials. There you can find ‘Applications’ menu click on that and click ‘Sandbox Accounts’ from the left menu. There you can find your email with ‘– facilitator’ that is you PayPal facilitator email address which will receive funds from users. Then click ‘Create Account’ at the right of the page. Create test accounts for make transactions. Make sure that ‘Account Type’ – ‘Personal’ has been checked. Now you have the both facilitator email address and test account email address. Then we will start the coding phase now. Download the simple ready to use PayPal integration script using PHP from below by clicking download icon. And change the line as like instructed below to use this PayPal integration code.
Step 1 Open paypal.php:
Change the below mentioned lines,
1
2 define('EMAIL_ADD', 'notifyemail@anydomain.com'); // define any notification email
define('PAYPAL_EMAIL_ADD', 'anyname-facilitator@domain.com'); // facilitator email
which used to receive payments.
Constant EMAIL_ADD is for receive notifications about the transactions like is it completed, pending and all. You will get emails by notification during IPN.
Constant PAYPAL_EMAIL_ADD is the mail which will receive funds from the users. Define the facilitator email address here. Define the original PayPal facilitator address here before site goes live.
Step 2 Design the form:
Design the form with mentioned fields and addition custom fields if you need.
NOTE: Remove ‘?sandbox=1’ from thw form action for live transactions.
Step 3 Post to a page:
Post the form to a page where you need to send the form data to PayPal. In this page we are going send the values to the paypal.php.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 $this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$p->add_field('business', PAYPAL_EMAIL_ADD); // Call the facilitator eaccount
$p->add_field('cmd', $_POST["cmd"]); // cmd should be _cart for cart checkout
$p->add_field('upload', '1');
$p->add_field('return', $this_script.'?action=success'); // return URL after the transaction got over
$p->add_field('cancel_return', $this_script.'?action=cancel'); // cancel URL if the trasaction was cancelled during half of the transaction
$p->add_field('notify_url', $this_script.'?action=ipn'); // Notify URL which received IPN (Instant Payment Notification)
$p->add_field('currency_code', $_POST["currency_code"]);
$p->add_field('invoice', $_POST["invoice"]);
$p->add_field('item_name_1', $_POST["product_name"]);
$p->add_field('item_number_1', $_POST["product_id"]);
$p->add_field('quantity_1', $_POST["product_quantity"]);
$p->add_field('amount_1', $_POST["product_amount"]);
$p->add_field('first_name', $_POST["payer_fname"]);
$p->add_field('last_name', $_POST["payer_lname"]);
$p->add_field('address1', $_POST["payer_address"]);
$p->add_field('city', $_POST["payer_city"]);
$p->add_field('state', $_POST["payer_state"]);
$p->add_field('country', $_POST["payer_country"]);
$p->add_field('zip', $_POST["payer_zip"]);
$p->add_field('email', $_POST["payer_email"]);
$p->submit_paypal_post(); // POST it to paypal
Save the form data before posted to PayPal like coded above. In this step the transaction will get started.
After the transaction got completed you will get an email to your Notification Email (EMAIL_ADD) regarding the transaction process. First you will get an email. Find ‘payment_status’ on that mail body. It will shows as ‘Pending’. Now the transaction is in pending status. Until PayPal sends ‘payment_status = Completed’ the transaction will be in the pending status.
Note: Make sure about the transaction id, payment status and invoice number for further steps.
Step 4 IPN (Instant Payment Notification):
PayPal has a module called IPN which means Instant Payment Notification. This will send you the transaction details from PayPal Server to your Server directly through posting data values in POST method.
Go to your PayPal sandbox account and go to ‘Application -> IPN Simulator’ paste the URL in IPN handler URL which want to receive the IPN Notifications. We had already mentioned the notify_url above. Paste the URL and choose ‘Transaction type’ as cart checkout. You will get number of fields. The field label will represent you the POST parameter name. No need to fill everything, but you should provide the txn_id (which you got from PayPal screen after transaction completion), choose payment_status as completed and fill invoice for further process. Then click on ‘Send IPN’ button. You will get the IPN details to the IPN URL and to the notification email either you got ‘IPN sent successfully’ or ‘sorry couldn’t send IPN’
Wait and check your email. You will get the mail(s) from IPN. Find on the payment_status. Make sure it got completed.
Save the data in your database. Check the payment_status is ‘completed’ then raise other stuffs such as sending invoice email and so on.
Notes (Before Live):
Remove 'sandbox=1' from the form action before your app goes live in index.php file.
Change the Notify email to other log email address or you will get hundreds of emails.
Change the facilitator account to a live account.
I have implemented this simple PayPal integration code and working fine in many of shopping cart projects and my projects contains checkout. Donwload this simple and ready to use script for your projects from below download link. Happy coding!
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
BLOG
Sending HTTP POST Request In Java
lets assume this URL...
http://www.example.com/page.php?id=10
(Here id needs to be sent in a POST request)
I want to send the id = 10 to the server's page.php, which accepts it in a POST method.
How can i do this from within Java?
I tried this :
URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();
But I still can't figure out how to send it via POST
Updated Answer:
Since some of the classes, in the original answer, are deprecated in the newer version of Apache HTTP Components, I'm posting this update.
By the way, you can access the full documentation for more examples here.
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
// do something useful
} finally {
instream.close();
}
}
Original Answer:
I recommend to use Apache HttpClient. its faster and easier to implement.
PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.
for more information check this url: http://hc.apache.org
String rawData = "id=10";
String type = "application/x-www-form-urlencoded";
String encodedData = URLEncoder.encode( rawData );
URL u = new URL("http://www.example.com/page.php");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());
The first answer was great, but I had to add try/catch to avoid Java compiler errors.
Also, I had troubles to figure how to read the HttpResponse with Java libraries.
Here is the more complete code :
/*
* Create the POST request
*/
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
/*
* Execute the HTTP Request
*/
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
A simple way using Apache HTTP Components is
Request.Post("http://www.example.com/page.php")
.bodyForm(Form.form().add("id", "10").build())
.execute()
.returnContent();
Take a look at the Fluent API
Call HttpURLConnection.setRequestMethod("POST") and HttpURLConnection.setDoOutput(true); Actually only the latter is needed as POST then becomes the default method.
Copyright © 2011 - All Rights Reserved - Softron.in
Template by Softron Technology