Welcome to www.HAS.lv - programmējam HTML.

Register now to gain access to all of our features. Once registered and logged in, you will be able to contribute to this site by submitting your own content or replying to existing content. You'll be able to customize your profile, receive reputation points as a reward for submitting content, while also communicating with other members via your own private inbox, plus much more! This message will be removed once you have signed in.

Sign in to follow this  
Followers 0
crelix

PayPal Integrācija (IPN Problēma)

Vēlos ieviest savā mājaslapā PayPal noreiķinus. Šobrīd testēju uz PayPal Sandbox. (Izmantoju tutorial, ja nepieciešams varu aizsūtīt linku PM, lai nav reklāma)

Problēma ir tajā, ka PayPal's izvada, ka darījums ir veikts, bet datubāzē dati netiek ievietoti un serveris izmet erroru.

PayPal uzstādijumi : Attēls

PayPal

Un rezultāts 

<h1>Your payment has failed.</h1>

PayPal cart:

  public function selectItems(){

    $paypalURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
    $paypalID = 'crelix-facilitator@car-paradise.org';

    ?>
    <div class="container"><?php

    $stmt = $this->conn->prepare("SELECT * FROM shop_items");
    $stmt->execute();
    $result = $stmt->fetchAll();

    foreach($result as $item){
      ?>
      <div class="proBox">
        <img src="/Web/Images/Shop/<?php echo $item['image']; ?>"/>
        <p>Name: <?php echo $item['name']; ?></p>
        <p>Price: <?php echo $item['price']; ?></p>
        <form target="_self" 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; ?>">
            <input type='hidden' name='notify_url' value='http://www.car-paradise.org/AdminPanel/Pages/ShopOrders.php'>

            <!-- Specify a PayPal Shopping Cart Add to Cart button. -->
            <input type="hidden" name="cmd" value="_cart">
            <input type="hidden" name="add" value="1">

            <!-- Specify details about the item that buyers will purchase. -->
            <input type="hidden" name="item_name" value="<?php echo $item['name']; ?>">
            <input type="hidden" name="item_number" value="<?php echo $item['id']; ?>">
            <input type="hidden" name="amount" value="<?php echo $item['price']; ?>">
            <input type="hidden" name="currency_code" value="EUR">

            <input type='hidden' name='cancel_return' value='http://www.car-paradise.org/Web/Pages/Shop/Shop.php'>
            <input type='hidden' name='return' value='http://www.car-paradise.org/Web/Pages/Shop/Success.php'>


            <!-- Display the payment button. -->
            <input type="image" name="submit" src="https://www.paypalobjects.com/webstatic/en_US/i/btn/png/btn_addtocart_120x26.png" alt="Add to Cart">
            <img alt="" width="1" height="1" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif">
        </form>
      </div>
    <?php }?>
    </div>
    <?php
  }

 

Success.php

<?php

require_once("../../Style/UserNavigation.php");

$txn_id = $_GET['tx'];
$payment_gross = $_GET['amt'];
$currency_code = $_GET['cc'];
$payment_status = $_GET['st'];

if(!empty($txn_id)){
  //Check if payment data exists with the same TXN ID.
  $paymentResult = $db->query("SELECT * FROM shop_payments WHERE txn_id = '".$txn_id."'");
  if($paymentResult->num_rows > 0){
    //payment information
    $paymentRow = $paymentResult->fetch_assoc();
    $payment_id = $paymentRow['payment_id'];

    //order items details
    $orderItemResult = $db->query("SELECT p.name, i.quantity, i.gross_amount FROM shop_order_items as i LEFT JOIN products as p ON p.id = i.item_number WHERE payment_id = '".$payment_id."'");
    ?>
    <h1>Your payment has been successful.</h1>
    <h2>Payment ID: <?php echo $payment_id; ?></h2>
    <h2>Payment Gross: <?php echo '$'.$paymentRow['payment_gross'].' '.$paymentRow['currency_code']; ?></h2>
    <?php if($orderItemResult->num_rows > 0){ ?>
    <h3>Order Items</h3>
    <table style="width:50%">
        <tr>
            <th>#</th>
            <th>Product Name</th>
            <th>Quantity</th>
            <th>Gross Amount</th>
        </tr>
    <?php $i=0; while($item = $orderItemResult->fetch_assoc()){ $i++; ?>
        <tr>
            <td align="center"><?php echo $i; ?></td>
            <td align="center"><?php echo $item['name']; ?></td>
            <td align="center"><?php echo $item['quantity']; ?></td>
            <td align="center"><?php echo '$'.$item['gross_amount'].' '.$paymentRow['currency_code']; ?></td>
        </tr>
    <?php } ?>
    </table>
    <?php } ?>

<?php }else{ ?>
    <h1>Your payment has been successful.</h1>
    <h2>TXN ID: <?php echo $txn_id; ?></h2>
    <h2>Payment Gross: <?php echo '$'.$payment_gross.' '.$currency_code; ?></h2>
<?php } }else{ ?>
    <h1>Your payment has failed.</h1>
<?php } ?>
<a href="/Web/Pages/Shop/Shop.php">Back to products</a>

Un ShopOrders.php(IPN)

<?php
  require_once("../../Web/System/Config.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://www.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) {

      //Payment data
      $txn_id = $_POST['txn_id'];
      $payment_gross = $_POST['mc_gross'];
      $currency_code = $_POST['mc_currency'];
      $payment_status = $_POST['payment_status'];
      $payer_email = $_POST['payer_email'];

      //Check if payment data exists with the same TXN ID.
      $prevPayment = $db->query("SELECT payment_id FROM shop_payments WHERE txn_id = '".$txn_id."'");
      if($prevPayment->num_rows > 0){
          exit();
      }else{
          //Insert tansaction data into the database
          $insertPayment = $db->query("INSERT INTO shop_payments(txn_id,payment_gross,currency_code,payment_status,payer_email) VALUES('".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."','".$payer_email."')");
          if($insertPayment){
              //Insert order items into the database
              $payment_id = $db->insert_id;
              $num_cart_items = $_POST['num_cart_items'];
              for($i=1;$i<=$num_cart_items;$i++){
                  $order_item_number = $_POST['item_number'.$i];
                  $order_item_quantity = $_POST['quantity'.$i];
                  $order_item_gross_amount = $_POST['mc_gross_'.$i];
                  $insertOrderItem = $db->query("INSERT INTO shop_order_items(payment_id,item_number,quantity,gross_amount) VALUES('".$payment_id."','".$order_item_number."','".$order_item_quantity."','".$order_item_gross_amount."')");
              }
          }
      }
}

 

0

Share this post


Link to post
Share on other sites

Man liekas, ka pašam ar kkas līdzīgs ir bijis, rekur IPN kods, šitas man strādāja:

	// STEP 1: read POST data
	// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
	// Instead, read raw POST data from the input stream.
	$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 IPN message sent from PayPal and prepend 'cmd=_notify-validate'
	$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";
	}

	// Step 2: POST IPN data back to PayPal to validate
	$ch = curl_init('https://ipnpb.paypal.com/cgi-bin/webscr');
	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_SSL_VERIFYPEER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
	// In wamp-like environments that do not come bundled with root authority certificates,
	// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set
	// the directory path of the certificate as shown below:
	// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
	if ( !($res = curl_exec($ch)) ) {
	  // error_log("Got " . curl_error($ch) . " when processing IPN data");
	  curl_close($ch);
	  exit;
	}
	curl_close($ch);

	if (strcmp ($res, "VERIFIED") == 0) {

		// maksājums veiksmīgs, db kodi....

	} else if (strcmp ($res, "INVALID") == 0) {

	}

 

0

Share this post


Link to post
Share on other sites

Paldies, tik vaina, laikam, man ir citur. Jo arī ar šo kodu ir tā pati problēma.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0