Paypal Integration

Hello everyone,

I am creating a test page with a test paypal buy now button. After the user has paid and is being redirected back to my site I want to print a message like “Thank you for paying, continue to the next step >>”

I failed to understand how to realize (by code) that the payment was made or not.

So, here’s my code:
paypal.php (IPN listener)
[php]class Paypal_IPN {
/**
* @var string $_url The paypal url to go to through cURL
/
private $_url;
/
*
* @param string $mode ‘live’ or ‘sandbox’
*/
public function __construct($mode = ‘live’) {
if ($mode == ‘live’)
$this->_url = ‘https://www.paypal.com/cgi-bin/webscr’;
else
$this->_url = ‘https://www.sandbox.paypal.com/cgi-bin/webscr’;
}
public function run() {
$postFields = ‘cmd=_notify-validate’;

	foreach($_POST as $key => $value)
	{
		$postFields .= "&$key=".urlencode($value);
	}

	$ch = curl_init();

	curl_setopt_array($ch, array(
		CURLOPT_URL => $this->_url,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_SSL_VERIFYPEER => false,
		CURLOPT_POST => true,
		CURLOPT_POSTFIELDS => $postFields
	));
	
	$result = curl_exec($ch);
	curl_close($ch);
	
	$fh = fopen('result.txt', 'w');
	fwrite($fh, $result . ' -- ' . $postFields);
	fclose($fh);
}

}[/php]

When I use the IPN Simulator the file result.txt is created and the IPN is stored inside.

test.php is the page the user visits and clicks on the “Buy Now” button.
test.php

[php]

require_once('paypal.php'); $paypal = new Paypal_IPN('sandbox'); $paypal->run(); if (strcmp ($result, "VERIFIED") == 0) { // The IPN is verified, process it: // check whether the payment_status is Completed // check that txn_id has not been previously processed // check that receiver_email is your Primary PayPal email // check that payment_amount/payment_currency are correct // process the notification
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];

// IPN message values depend upon the type of notification sent.
// To loop through the &_POST array and print the NV pairs to the screen:
foreach($_POST as $key => $value) {
  echo $key." = ". $value."<br>";
}
echo 'YES! PAYMENT WAS MADE!';

} else if (strcmp ($result, “INVALID”) == 0) {
// IPN invalid, log for manual investigation
echo “The response from IPN was: " .$result .”";
}[/php]

Everything is currently being done a a Paypal sandbox account. Any suggestions?

In .Net here’s how it’s done and I can explain it better, but hopefully you can apply it to your PHP Code.

This is the one I use for the IPN For Paypal

[php] Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Post back to either sandbox or live
Try
Dim strSandbox As String = “https://www.sandbox.paypal.com/cgi-bin/webscr
Dim strLive As String = “https://www.paypal.com/cgi-bin/webscr
Dim req As HttpWebRequest

       'Put in Live mode
        If GetFormVariable("test_ipn") = "1" Then
            req = CType(WebRequest.Create(strSandbox), HttpWebRequest)
        Else
            req = CType(WebRequest.Create(strLive), HttpWebRequest)
        End If

        'Set values for the request back
        req.Method = "POST"
        req.ContentType = "application/x-www-form-urlencoded"
        Dim Param() As Byte = Request.BinaryRead(HttpContext.Current.Request.ContentLength)
        Dim strRequest As String = Encoding.ASCII.GetString(Param)
        strRequest = strRequest + "&cmd=_notify-validate"
        req.ContentLength = strRequest.Length

        'for proxy
        'Dim proxy As New WebProxy(New System.Uri("http://url:port#"))
        'req.Proxy = proxy

        'Send the request to PayPal and get the response
        Dim streamOut As StreamWriter = New StreamWriter(req.GetRequestStream(), Encoding.ASCII)
        streamOut.Write(strRequest)
        streamOut.Close()
        Dim streamIn As StreamReader = New StreamReader(req.GetResponse().GetResponseStream())
        Dim strResponse As String = streamIn.ReadToEnd()
        streamIn.Close()

     'If they Response I get back says "VERIFIED" then paypal sent the IPN request

        If strResponse = "VERIFIED" Then

            Dim strrecord As String = ""

            For Each vkey In Request.Form.AllKeys
                strrecord += vkey & " - " & Request.Form(vkey) & "<br>"
            Next
           
            'I'm just logging all the information that paypal sent for review.
            LogAdminError(strrecord, "test")

            'check that payment_amount/payment_currency are correct
            If Request.Form("mc_currency").ToString.ToLower.Trim <> "usd" Then
                LogAdminTask("Currency listed as" & Request.Form("mc_currency").ToString & " Transaction was not process - check paypal account for Transaction ID: " & Request.Form("txn_id").ToString)
                Exit Sub
            End If

            'check that receiver_email is your Primary PayPal email
            If Request.Form("receiver_email").ToString.ToLower.Trim <> "Paypal Email address" And Request.Form("receiver_email").ToString.ToLower.Trim <> "Paypal Test Account Email address" Then
                LogAdminTask("Receiver Email  listed as" & Request.Form("receiver_email").ToString & " Transaction was not process - check paypal account for Transaction ID: " & Request.Form("txn_id").ToString)
                Exit Sub
            End If


            'process payment - This is where I activate whatever services was bought, or de-activate is something was cancelled. 
            ProcessPayment()

            'Insert the paypal record - Just storing the transaction on my side from paypal
            InsertIPN()


        ElseIf strResponse = "INVALID" Then
            LogAdminTask("Paypal Response was is invalid, please check")
            'log for manual investigation
        Else
            LogAdminTask("Paypal Response was not verified, please check")
            'Response wasn't VERIFIED or INVALID, log for manual investigation
        End If
    Catch ex As Exception
        LogAdminError(ex.Message.ToString & ex.StackTrace.ToString, "Page_load - PPIPN.aspx.vb")
    End Try

End Sub[/php]

Unfortunately i’m not a big fan of .NET for the same reason that i’m looking at your code and all I can make of it is that you did something quite similar to what I have. I’m afraid that is not helping with my issue, thanks though, I appreciate the help!

Sponsor our Newsletter | Privacy Policy | Terms of Service