PayPal IPN does not store in MySql

0

I'm having problems with the IPN of PayPal , it's my first time integrating this gateway and the data that comes in the documentation was a bit scrambled.

create 3 files to process the payment, paquetes ipn and success .

I'm not using the buttons so I create variables for the form that is sent to PayPal found in packages

<?php

$loggedUser = $_SESSION["id"];

$date = getdate();

$day = $date["mday"];
$month = $date["mon"];
$year = $date["year"];

//PayPal variables
$paypalURL     = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
$paypalID     = '[email protected]';
$successURL = 'http://prueba.com/success';
$cancelURL     = 'http://prueba.com/cancel';
$notifyURL     = 'http://prueba.com/paypal_ipn';

$itemName = 'Suscripcion 1!';
$itemName2 = 'Suscripcion 2!';
$itemName3 = 'Suscripcion 3!';
$itemNumber = 'MS/'.$day.'/'.$month.'/'.$year.'/'.$loggedUser;

//subscription price for one month
$itemPrice = 0.02;

and that's how it turns out the form that is being the button created by me assigning the variables

<form action="<?php echo $paypalURL; ?>" method="post">
        <!-- identify your business so that you can collect the payments -->
        <input type="hidden" name="business" value="<?php echo $paypalID; ?>">
        <!-- specify a subscriptions button. -->
        <input type="hidden" name="cmd" value="_xclick-subscriptions">
        <!-- specify details about the subscription that buyers will purchase -->
        <input type="hidden" name="item_name" value="<?php echo $itemName; ?>">
        <input type="hidden" name="item_number" value="<?php echo $itemNumber; ?>">
        <input type="hidden" name="currency_code" value="MXN">
        <input type="hidden" name="a3" id="paypalAmt" value="<?php echo $itemPrice; ?>">
        <input type="hidden" name="p3" id="paypalValid" value="1">
        <input type="hidden" name="t3" value="M">
        <!-- custom variable user ID -->
        <input type="hidden" name="custom" value="<?php echo $loggedUser; ?>">
        <!-- specify urls -->
        <input type="hidden" name="cancel_return" value="<?php echo $cancelURL; ?>">
        <input type="hidden" name="return" value="<?php echo $successURL; ?>">
        <input type="hidden" name="notify_url" value="<?php echo $notifyURL; ?>">
        <!-- display the payment button -->
        <input class="paypal_button" type="submit" value="Comprar Suscripción">
</form>

everything is sent correctly to PayPal but at the moment that the data should be returned in ipn and success the only thing that is received by get is the following

http://exampledomain.com/success?auth=AwayQdhjzADAexJ4X-hVqtlSrIzEW1KUFaLNIMlJg8Qhd6LkVXizKvsoahKvZkQN4xe1MjohmDqn3NaFS-lTsBQ&form_charset=UTF-8

in ipn I have the data as follows

<?php

/*
 * Read POST data
 * reading posted data directly from $_POST causes serialization
 * issues with array data in POST.
 * Reading raw POST data from input stream instead.
 */        
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
    $keyval = explode ('=', $keyval);
    if (count($keyval) == 2)
        $myPost[$keyval[0]] = urldecode($keyval[1]);
}

// Read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
    $get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
    if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
        $value = urlencode(stripslashes($value));
    } else {
        $value = urlencode($value);
    }
    $req .= "&$key=$value";
}

/*
 * Post IPN data back to PayPal to validate the IPN data is genuine
 * Without this step anyone can fake IPN data
 */
$paypalURL = "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr";
$ch = curl_init($paypalURL);
if ($ch == FALSE) {
    return FALSE;
}
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);

// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close', 'User-Agent: company-name'));
$res = curl_exec($ch);

/*
 * Inspect IPN validation result and act accordingly
 * Split response headers and payload, a better way for strcmp
 */ 
$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));
if (strcmp($res, "VERIFIED") == 0 || strcasecmp($res, "VERIFIED") == 0) {
    //Include DB configuration file
    //Database credentials
    $dbHost = 'localhost';
    $dbUsername = 'User';
    $dbPassword = 'Pass';
    $dbName = 'Name';

    //Connect with the database
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

    //Display error if failed to connect
    if ($db->connect_errno) {
        printf("Connect failed: %s\n", $db->connect_error);
        exit();
    }

    $unitPrice = 25;

    //Payment data
    $subscrid = $_POST['subscr_id'];
    $payerwemail = $_POST['payer_email'];
    $itemnumber = $_POST['item_number'];
    $txnid = $_POST['txn_id'];
    $paymentgross = $_POST['mc_gross'];
    $currencycode = $_POST['mc_currency'];
    $paymentstatus = $_POST['payment_status'];
    $custom = $_POST['custom'];
    $subscrmonth = ($payment_gross/$unitPrice);
    $subscrdays = ($subscr_month*30);
    $subscrdate_from = date("Y-m-d H:i:s");
    $subscrdateto = date("Y-m-d H:i:s", strtotime($subscrdatefrom. ' + '.$subscrdays.' days'));

    if(!empty($txn_id)){
        //Check if subscription data exists with the same TXN ID.
        $prevPayment = $db->query("SELECT id FROM usersubscriptions WHERE txnid = '".$txnid."'");
        if($prevPayment->num_rows > 0){
            exit();
        }else{
            //Insert tansaction data into the database
            $insert = $db->query("INSERT INTO usersubscriptions(userid,validity,validfrom,validto,itemnumber,txnid,paymentgross,currencycode,subscrid,paymentstatus,payerwemail) VALUES('".$custom."','".$subscrmonth."','".$subscrdatefrom."','".$subscrdateto."','".$itemnumber."','".$txnid."','".$paymentgross."','".$currencycode."','".$subscrid."','".$paymentstatus."','".$payerwemail."')");

            //Update subscription id in users table
            if($insert){
                $subscriptionid = $db->insertid;
                $update = $db->query("UPDATE users SET subscriptionid = {$subscriptionid} WHERE id = {$custom}");
            }
        }
    }
}
die;

I know I'm vulnerable to an SQL injection but that's not the problem since for obvious reasons I'll change everything to PDO

and in success I have the following

<?php
//Include DB configuration file
include 'dbconnect.php';

if(!empty($_GET['item_number']) && !empty($_GET['tx']) && !empty($_GET['amt']) && $_GET['st'] == 'Completed'){
    //get transaction information from query string
    $item_number = $_GET['item_number'];
    $txn_id = $_GET['tx'];
    $payment_gross = $_GET['amt'];
    $currency_code = $_GET['cc'];
    $payment_status = $_GET['st'];
    $custom = $_GET['cm'];

    //Check if subscription data exists with the TXN ID
    $prevPaymentResult = $db->query("SELECT * FROM usersubscriptions WHERE txnid = '".$txn_id."'");

    if($prevPaymentResult->num_rows > 0){
        //get subscription info from database
        $paymentRow = $prevPaymentResult->fetch_assoc();

        //prepare subscription html to display
        $phtml  = '<h5 class="success">Thanks for payment, your payment was successful. Payment details are given below.</h5>';
        $phtml .= '<div class="paymentInfo">';
        $phtml .= '<p>Payment Reference Number: <span>MS'.$paymentRow['id'].'</span></p>';
        $phtml .= '<p>Transaction ID: <span>'.$paymentRow['txn_id'].'</span></p>';
        $phtml .= '<p>Paid Amount: <span>'.$paymentRow['payment_gross'].' '.$paymentRow['currency_code'].'</span></p>';
        $phtml .= '<p>Validity: <span>'.$paymentRow['valid_from'].' to '.$paymentRow['valid_to'].'</span></p>';
        $phtml .= '</div>';
    }else{
        $phtml = '<h5 class="error">Your payment was unsuccessful, please try again.</h5>';
    }
}elseif(!empty($_GET['item_number']) && !empty($_GET['tx']) && !empty($_GET['amt']) && $_GET['st'] != 'Completed'){
    $phtml = '<h5 class="error">Your payment was unsuccessful, please try again.</h5>';
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>PayPal Subscriptions Payment Payment Status</title>
    <meta charset="utf-8">
</head>
<body>
<div class="container">
    <h1>PayPal Subscriptions Payment Status</h1>
    <!-- render subscription details -->
    <?php echo !empty($phtml)?$phtml:''; ?>
</body>
</html>

I have changed the catch again and again and it still does not work, I hope someone can help me to know what I'm wrong with or what code to take so I can insert the data in the database

  

New code and error

In ipn change all values for the following

<?php

$nombre = $_SESSION["name"];
$apellido = $_SESSION["lastname"];
$nombreCompleto = $nombre.' '.$apellido;

$subscr_date_from = $this->issetCheck($post,'subscr_date');
$subscr_days = 30;
$subscr_date_to = date("Y-m-d H:i:s", strtotime($subscr_date_from. ' + '.$subscr_days.' days'));

class PayPal_IPN{
    function infotuts_ipn($im_debut_ipn) {

        define('SSL_P_URL', 'https://www.paypal.com/cgi-bin/webscr');
        define('SSL_SAND_URL', 'https://www.sandbox.paypal.com/cgi-bin/webscr');
        $hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
        if (!preg_match('/paypal\.com$/', $hostname)) {
            $ipn_status = 'Validation post isn\'t from PayPal';
            if ($im_debut_ipn == true) {
                // mail test
            }

            return false;
        }

        // parse the paypal URL
        $paypal_url = ($_REQUEST['test_ipn'] == 1) ? SSL_SAND_URL : SSL_P_URL;
        $url_parsed = parse_url($paypal_url);

        $post_string = '';
        foreach ($_REQUEST as $field => $value) {
            $post_string .= $field . '=' . urlencode(stripslashes($value)) . '&';
        }
        $post_string.="cmd=_notify-validate"; // append ipn command
        // get the correct paypal url to post request to
        $paypal_mode_status = $im_debut_ipn; //get_option('im_sabdbox_mode');
        if ($paypal_mode_status == true){
            $fp = fsockopen('ssl://www.sandbox.paypal.com', "443", $err_num, $err_str, 60);
        } else{
            $fp = fsockopen('ssl://www.paypal.com', "443", $err_num, $err_str, 60);
        }

        $ipn_response = '';

        if (!$fp) {
            // could not open the connection.  If loggin is on, the error message
            // will be in the log.
            $ipn_status = "fsockopen error no. $err_num: $err_str";
            if ($im_debut_ipn == true) {
                echo 'fsockopen fail';
            }
            return false;
        } else {
            // Post the data back to paypal
            fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n");
            fputs($fp, "Host: $url_parsed[host]\r\n");
            fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
            fputs($fp, "Content-length: " . strlen($post_string) . "\r\n");
            fputs($fp, "Connection: close\r\n\r\n");
            fputs($fp, $post_string . "\r\n\r\n");

            // loop through the response from the server and append to variable
            while (!feof($fp)) {
                $ipn_response .= fgets($fp, 1024);
            }
            fclose($fp); // close connection
        }

        // Invalid IPN transaction.  Check the $ipn_status and log for details.
        if (!preg_match("/VERIFIED/s", $ipn_response)) {
            $ipn_status = 'IPN Validation Failed';

            if ($im_debut_ipn == true) {
                echo 'Validation fail';
                print_r($_REQUEST);
            }
            return false;
        } else {
            $ipn_status = "IPN VERIFIED";
            if ($im_debut_ipn == true) {
                echo 'SUCCESS';

                }

            return true;
        }
    }

    function ipn_response($request){
        mail("[email protected]","My subject",print_r($request,true));
        $im_debut_ipn=true;
        if ($this->infotuts_ipn($im_debut_ipn)) {

            // if paypal sends a response code back let's handle it        
               if ($im_debut_ipn == true) {
                $sub = 'PayPal IPN Debug Email Main';
                $msg = print_r($request, true);
                $aname = 'infotuts';
              //mail send
            }

            // process the membership since paypal gave us a valid +
            $this->insert_data($request);
        }
    }

    function issetCheck($post,$key){
        if(isset($post[$key])){
            $return=$post[$key];
        } else {
            $return='';
        }
        return $return;
    }

    function insert_data($request){
        require_once('dbconnect.php');
        $post=$request;

        $datos = array(
            $idUser = $_SESSION["id"],
            $suscriptorId = $this->issetCheck($post,'subscr_id'),
            $name = $nombreCompleto,
            $nombrePlan = $this->issetCheck($post,'item_name'),
            $payerStatus = $this->issetCheck($post,'payer_status'),
            $payer_email = $this->issetCheck($post,'payer_email'),
            $payerId = $this->issetCheck($post,'payer_id'),
            $cantidad = $this->issetCheck($post,'mc_amount3'),
            $periodo = $this->issetCheck($post,'period3'),
            $diaSuscripcion = $this->issetCheck($post,'subscr_date'),
            $finalizaEn = $subscr_date_to,
            $autorizacion = $this->issetCheck($post,'auth')
        );

        $respuestaPago = ControladorPago::ctrCrearPago($datos);

        if ($respuestaPago = "ok") {
            $phtml = '<h5 class="error">Tu pago se ha generado correctamente.</h5>';
        } else {
            echo "eror";
        }
    }

    $obj = New PayPal_IPN();
    $obj -> ipn_response($_REQUEST);
}

?>

and the error that marks me in the log that my host creates is the following

[11-Jul-2018 20:32:12 UTC] PHP Parse error:  syntax error, unexpected '$obj' 
(T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST) in 
/home/ntkoeqcqx3ss/prueba/vista/modulos/ipn.php on line 144
    
asked by cesg.dav 11.07.2018 в 07:20
source

0 answers