I tried many threads on stackoverflow but nothing,i try for 2 days to integrate paypal payments with my php script.
(我在stackoverflow上尝试了很多线程,但是什么也没做,我尝试了2天以将贝宝付款与我的php脚本集成在一起。)
PayPalIPN.php:
(PayPalIPN.php:)
<?php
class PaypalIPN
{
/**
* @var bool $use_sandbox Indicates if the sandbox endpoint is used.
*/
private $use_sandbox = false;
/**
* @var bool $use_local_certs Indicates if the local certificates are used.
*/
private $use_local_certs = true;
/** Production Postback URL */
const VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
/** Sandbox Postback URL */
const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
/** Response from PayPal indicating validation was successful */
const VALID = 'VERIFIED';
/** Response from PayPal indicating validation failed */
const INVALID = 'INVALID';
/**
* Sets the IPN verification to sandbox mode (for use when testing,
* should not be enabled in production).
* @return void
*/
public function useSandbox()
{
$this->use_sandbox = true;
}
/**
* Sets curl to use php curl's built in certs (may be required in some
* environments).
* @return void
*/
public function usePHPCerts()
{
$this->use_local_certs = false;
}
/**
* Determine endpoint to post the verification data to.
* @return string
*/
public function getPaypalUri()
{
if ($this->use_sandbox) {
return self::SANDBOX_VERIFY_URI;
} else {
return self::VERIFY_URI;
}
}
/**
* Verification Function
* Sends the incoming post data back to PayPal using the cURL library.
*
* @return bool
* @throws Exception
*/
public function verifyIPN()
{
if ( ! count($_POST)) {
throw new Exception("Missing POST Data");
}
$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) {
// Since we do not want the plus in the datetime string to be encoded to a space, we manually encode it.
if ($keyval[0] === 'payment_date') {
if (substr_count($keyval[1], '+') === 1) {
$keyval[1] = str_replace('+', '%2B', $keyval[1]);
}
}
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
}
// Build the body of the verification post request, adding the _notify-validate command.
$req = 'cmd=_notify-validate';
$get_magic_quotes_exists = false;
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 the data back to PayPal, using curl. Throw exceptions if errors occur.
$ch = curl_init($this->getPaypalUri());
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);
// This is often required if the server is missing a global cert bundle, or is using an outdated one.
if ($this->use_local_certs) {
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/cert/cacert.pem");
}
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
$res = curl_exec($ch);
if ( ! ($res)) {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
curl_close($ch);
throw new Exception("cURL error: [$errno] $errstr");
}
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
if ($http_code != 200) {
throw new Exception("PayPal responded with http code $http_code");
}
curl_close($ch);
// Check if PayPal verifies the IPN data, and if so, return true.
if ($res == self::VALID) {
return true;
} else {
return false;
}
}
}
paypal_ipn.php:
(paypal_ipn.php:)
<?php
///////////////////////////////////////////////////////////////////////////////
// How to setup PayPal in your website using PHP + MYSQL
// Author: Ideal Kamerolli
// Check out our website for more tutorials like this: https://dopehacker.com
///////////////////////////////////////////////////////////////////////////////
namespace Listener;
//include PayPal IPN Class file (https://github.com/paypal/ipn-code-samples/blob/master/php/PaypalIPN.php)
require('PaypalIPN.php');
//include configuration file
require('core_config.php');
use PaypalIPN;
$ipn = new PaypalIPN();
if ($enable_sandbox) {$ipn->useSandbox();}
$verified = true;
$ipn->verifyIPN();
//reading $_POST data from PayPal
$data_text = "";
foreach ($_POST as $key => $value) {
$data_text .= $key . " = " . $value . "
";
}
// Checking if our paypal email address was changed during payment.
$receiver_email_found = false;
if (strtolower($_SESSION['user_email']) == strtolower($paypal_seller))
{
$receiver_email_found = true;
}
// Checking if price was changed during payment.
// Get product price from database and compare with posted price from PayPal
$correct_price_found = false;
$price = $_SESSION['total_checkout'];
if ($_POST["mc_gross"] == $price)
{
$correct_price_found = true;
return;
}
//Checking Payment Verification
$paypal_ipn_status = "PAYMENT VERIFICATION FAILED";
if ($verified) {
$paypal_ipn_status = "Email address or price mismatch";
if ($receiver_email_found || $correct_price_found) {
$paypal_ipn_status = "Payment has been verified";
// Check if payment has been completed and insert payment data to database
// if ($_POST["payment_status"] == "Completed") {
// uncomment upper line to exit sandbox mode
global $errors2, $succeses2, $woName;
$myID = $_SESSION['user_id'];
$total_checkout = $_SESSION['total_checkout'];
$queir = "SELECT * FROM `thbs_items_cart` WHERE `user_id`=$myID";
$restults = @mysqli_query($db, $queir)
or die ("SQL error(payment(b)):" .mysqli_error($db));;
if(@mysqli_num_rows($restults) > 0)
{
$item = mysqli_fetch_assoc($restults);
$woName = $item['item_name'];
$woPrice = $item['item_price'];
$woHot = $item['item_hot'];
$woTax = $item['item_tax'];
$woATax = $item['item_atax'];
$woInstant = $item['item_instant'];
$woTopic = $item['item_topic'];
$woStock = $item['item_stock'];
$woTimeline = $item['item_timeline'];
$woTimeNumber = $item['item_timenumber'];
$nextYears = date("Y-m-d", strtotime('+'.$woTimeNumber.' year'));
if($woTimeline == "y") { $woExpire_on = $nextYears; }
if($woTimeline == "m") { $woExpire_on = $nextMonths; }
if($woTimeline == "d") { $woExpire_on = $nextDays; }
if($woTimeline == "l") { $woExpire_on = "9999-21-21"; }
$woCategory = $item['item_category'];
if($woStock < 1)
{
array_push($errors2, "An item from your cart is out of stock.");
}
if(count($errors2) < 1)
{
$query4j = "UPDATE `thbs_users` SET `account_money`=`account_money`-'$total_checkout' WHERE `id`='$myID'";
mysqli_query($db, $query4j);
$query4jk = "DELETE FROM `thbs_items_cart` WHERE `user_id`='$myID'";
mysqli_query($db, $query4jk);
$querya = "INSERT INTO `thbs_sv_domains` (`svdo_user`, `svdo_name`, `svdo_price`,`svdo_status`, `svdo_instructions`, `svdo_instant`, `svdo_type`, `svdo_hot`, `svdo_expire_date`, `svdo_timeline`, `svdo_expired`, `svdo_date`, `svdo_ns1`, `svdo_ns2`, `svdo_ns3`, `svdo_ns4`, `svdo_ns5`, `svdo_WHOIS_protection`) VALUES ('$myID', '$woName', '$woPrice', 'Pending', 'none', '$woInstant', '$woCategory', '$woHot', '$woExpire_on', '$woTimeline', 0, CURDATE(), '$current_ns1', '$current_ns2', '$current_ns3', '$current_ns4', '$current_ns5', 0)";
mysqli_query($db, $querya)
or die ("SQL error(a - payment(b)):" .mysqli_error($db));
?><script>window.location.href = 'client_area?view_cart=1&validate_payment=1';</script><?php
}
}
$paypal_ipn_status = "Payment has been completed";
// }
// uncomment upper line to exit sandbox mode
}
} else {
$paypal_ipn_status = "Payment verification failed";
}
?>
payment checker:
(付款检查器:)
<?php
if(addon_activated('PayPal_Gateway') == "YES" && $_GET['pay_with'] == "PayPal")
{
include_once('content/addons/PayPal_Gateway/core_config.php');
include_once('content/addons/PayPal_Gateway/paypal_ipn.php');
if($_GET['success'] == 1 && $ipn == true)
{
global $errors2, $succeses2, $woName;
$myID = $_SESSION['user_id'];
$total_checkout = $_SESSION['total_checkout'];
$queir = "SELECT * FROM `thbs_items_cart` WHERE `user_id`=$myID";
$restults = @mysqli_query($db, $queir)
or die ("SQL error(payment(PayPal_Gateway - run.php)):" .mysqli_error($db));;
if(@mysqli_num_rows($restults) > 0)
{
$item = mysqli_fetch_assoc($restults);
$woName = $item['item_name'];
$woPrice = $item['item_price'];
$woHot = $item['item_hot'];
$woTax = $item['item_tax'];
$woATax = $item['item_atax'];
$woInstant = $item['item_instant'];
$woTopic = $item['item_topic'];
$woStock = $item['item_stock'];
$woTimeline = $item['item_timeline'];
$woTimeNumber = $item['item_timenumber'];
$nextYears = date("Y-m-d", strtotime('+'.$woTimeNumber.' year'));
$nextMonths = date("Y-m-d", strtotime('+'.$woTimeNumber.' month'));
$nextDays = date("Y-m-d", strtotime('+'.$woTimeNumber.' day'));
if($woTimeline == "y") { $woExpire_on = $nextYears; }
if($woTimeline == "m") { $woExpire_on = $nextMonths; }
if($woTimeline == "d") { $woExpire_on = $nextDa