Paypal - Accept Credit Cards Online
PayPal - one of the pioneers of internet credit card processing
without a merchant account. There are no set up fees, and the basic transaction
costs are very low: $.30 plus 2.2 to 2.9%. It's a very easy way to facilitate
payment and it has a wide international program. You can set up individual buttons
to sell specific items from your web site. International merchants welcome and
multiple currencies supported. Setup takes a few days as they verify your banking
and credit card information. PayPal also allows for a "trial period"
that delays the actual processing of the credit card - useful if you want to
allow your customers to try your services for a 30-day free trial, for example.
Programming for Paypal Merchant Account Setup
About IPN
Instant Payment Notification (IPN) allows you to integrate your PayPal payments
with your website's back-end operations, so you get immediate notification and
authentication of the PayPal payments you receive.
PayPal IPN is used by communicating via HTTP. In essence, PayPal IPN enables
your system to integrate real time credit card notification of a payments from
PayPal.
How to use?
To use the PayPal Instant Payment Notification with PHP you need to receive
a POST from https://www.paypal.com/cgi-bin/webscr and then it must post the
information, including the encrypted code, back to the secure PayPal URL.
PHP currently does support posting to a secure server (https://) with a SSL
client connection if your using PHP 4.3 complied with OpenSSL.
Here are our example
IPN PHP scripts using SSL.
To use the scripts below you need:
A server that supports
fsockopen. (yahoo and a lot of other servers do not support fsockopen)
Write your own MySQL database handling functions.
IPN Notification Script
Let us see about one free php resource for developers wishing to integrate
their projects into the PayPal Instant Payment Notification service, more genuinely
known as IPN.
Just what you need to do is to set the database details found in $_Config array.
And need to update the functions given for each of the Payment_Status, like
update your local database & mailings.
Config Variables
//--------------------------------------------------
// Update your Database Details here
//--------------------------------------------------
$_Config["DBHost"]
= "localhost";
$_Config["DBUserName"] = "root";
$_Config["DBPassword"] = "";
$_Config["DBDatabaseName"] = "activemed";
Write Log File
This is where the log file will be created whenever the IPN script
integrated at your backend. Note that this file must have write permission
//-----------------------------------------------------------
// Write the Log in
ipn.log file. It should have write permission
//-----------------------------------------------------------
$myLogFile = fopen("ipn.log","a");
fwrite($log, "nnipn - " . gmstrftime ("%b %d %Y %H:%M:%S",
time()) . "n");
Connect
to DB
$myConnection
= mysql_connect($_Config["DBHost"],$_Config["DBUserName"],$_Config["DBPassword"])
or die("Could not connect to the server") ;
$myDB = mysql_select_db($_Config["DBDatabaseName"],$myConnection)
or die("database failed");
Standard
PayPal Code
T he next step is to create a reply to validate the PayPal post. This bit of
code first creates a new array ($postvars) containing all of the values posted
from PayPal. Then it begins a reply message ($req), with 'cmd=_notify-validate'.
Using a 'for' loop, it adds a list of posted vars in the format 'variable=value
.
//-----------------------------------------------------------
// Read post from PayPal system and create reply
// starting with: 'cmd=_notify-validate'...
// then repeating all values sent - VALIDATION.
//-----------------------------------------------------------
$postvars = array();
while (list ($key, $value) = each ($HTTP_POST_VARS)) {
$postvars[] = $key;
}
$req = 'cmd=_notify-validate';
for ($var = 0; $var < count ($postvars); $var++) {
$postvar_key = $postvars[$var];
$postvar_value = $$postvars[$var];
$req .= "&" . $postvar_key . "=" . urlencode ($postvar_value);
}
Then create an HTTP header for the reply message, open a connection...
//--------------------------------------------
// Create message to post back to PayPal...
// Open a socket to the PayPal server...
//--------------------------------------------
$header .= "POST /cgi-bin/webscr HTTP/1.0rn";
$header .= "Content-Type: application/x-www-form-urlencodedrn";
$header .= "Content-Length: " . strlen ($req) . "rnrn";
$fp = fsockopen ("www.paypal.com", 80, $errno, $errstr, 30);
Next to write the transaction details to the log file.
The log file is useful for debugging problems. You'll ideally never lose any
details, and if the database is down for any reason, you need a backup..
//---------------------------------------------
fwrite($log, "Vals: ". $invoice." ". $receiver_email."
". $item_name." ". $item_ number." ". $quantity."
". $payment_status." ". $pending_reason." ".$payment_dat
e." ". $payment_gross." ". $payment_fee." ". $txn_id."
". $txn_type." ". $first_ name." ". $last_name."
". $address_street." ". $address_city." ". $address_state
. " ".$address_zip." ". $address_country." ".
$address_status." ". $payer_email. " ". $payer_status."
". $payment_type." ". $notify_version." ". $verify_sign.
" n");
Check Connection...
The variables $errstr and $errno are system variables which report details on
the last error.
//----------------------------------------------------------------------
// Check HTTP connection made to PayPal OK, If not, print an error msg
//----------------------------------------------------------------------
if (!$fp) {
echo "$errstr ($errno)";
fwrite($log, "Failed to open HTTP connection!");
$res = "FAILED";
}
Final Verification
At last, the string of posted variables ($req) is sent to PayPal's server. When
it receives it - the server gives a 'VERIFIED' response if the transaction was
real and successful.
//--------------------------------------------------------
// If connected OK, write the posted values back, then...
//--------------------------------------------------------
else {
fputs ($fp, $header . $req);
//-------------------------------------------
// ...read the results of the verification...
// If VERIFIED = continue to process the TX...
//-------------------------------------------
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
If payment is complete,
get the password from the database.
If the payment status is 'Completed'... The payment wasn't by e-check. The transaction's
complete.
Using the 'while'
construct to get the data into a local variable is just a convenience... We
know that only 1 row will come back from the query.
//----------------------------------------------------------------------
// If the payment_status=Completed... Get the password for the product
// from the DB and email it to the customer. Do the completed Process in
// the function called completedProcess.
//----------------------------------------------------------------------
if (strcmp ($payment_status, "Completed") == 0) {
completedProcess();
}
Handle Incomplete
Transactions
Inform the customer, and also inform yourself that something needs doing.
//----------------------------------------------------------------------
// If the payment_status is NOT Completed...
// Do the InComplete process in the function inCompleteProcess();
//----------------------------------------------------------------------
else {
inCompleteProcess();
}
Deal with 'Unverified'
transactions
If, for example, the transaction you just processed didn't originate with PayPal,
but was an attempted hack - it would cause this error to occur. An invalid transaction
needs human intervention.
//----------------------------------------------------------------
// ..If UNVerified - It's 'Suspicious' and needs investigating!
// Do the unVerified process in the function unVerifiedProcess function.
//----------------------------------------------------------------
else {
unVerifiedProcess();
}
}
}
Insert Details Into DB
The '"' is placed around each of the variable to ensure that they appear
in double quotes in the query string. This ensures that whatever they contain,
they'll get inserted.
//--------------------------------------
// Insert Transaction details into DB.
//--------------------------------------
$qry = "INSERT into psales (
invoice, receiver_email, item_name, item_number, quantity, payment_status, pendi
ng_reason, payment_date, payment_gross, payment_fee, txn_id, txn_type, first_nam
e, last_name, address_street, address_city, address_state, address_zip, address_
country, address_status, payer_email, payer_status, payment_type, notify_version
, verify_sign )
VALUES
( "$invoice", "$receiver_email", "$item_name",
"$item_number", "$quanti ty", "$payment_status",
"$pending_reason", "$payment_date", "$payment_gr
oss", "$payment_fee", "$txn_id", "$txn_type",
"$first_name", "$last_na me", "$address_street",
"$address_city", "$address_state", "$address_zip
", "$address_country", "$address_status", "$payer_email",
"$payer_status ", "$payment_type", "$notify_version",
"$verify_sign" ) ";
$result = mysql_query($qry,$myDB);
Close up.
//-------------------------------------------
// Close PayPal Connection, Log File and DB.
//-------------------------------------------
fclose ($fp);
fclose ($log);
mysql_close($myDB);
?>
|